Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload File to Firebase Storage using Admin SDK

According to the Docs, I have to pass the filename to the function in order to upload a file.

// Uploads a local file to the bucket
await storage.bucket(bucketName).upload(filename, {
  // Support for HTTP requests made with `Accept-Encoding: gzip`
  gzip: true,
  metadata: {
    // Enable long-lived HTTP caching headers
    // Use only if the contents of the file will never change
    // (If the contents will change, use cacheControl: 'no-cache')
    cacheControl: 'public, max-age=31536000',
  },
});

I am using Firebase Admin SDK (Nodejs) in my server side code and clients send file in form-data which i get as File Objects. How then do i upload this when the function accepts only filename leading to filepath.

I want to be able to do something like this


app.use(req: Request, res: Response) {
 const file = req.file;
// upload file to firebase storage using admin sdk
}

like image 931
Chima Precious Avatar asked Mar 11 '19 22:03

Chima Precious


People also ask

What is the use of Firebase Admin SDK?

The Admin SDK is a set of server libraries that lets you interact with Firebase from privileged environments to perform actions like: Read and write Realtime Database data with full admin privileges.

How do I upload files to Firebase storage in node JS?

Set up firebase project Choose a name for your project. Firebase will then set up your project. For storing the files click on the “storage” button on the left navigation pane. Click “Get started” button, Then a modal will open which has the security rules for your cloud storage.


1 Answers

Since the Firebase Admin SDK just wraps the Cloud SDK, you can use the Cloud Storage node.js API documentation as a reference to see what it can do.

You don't have to provide a local file. You can also upload using node streams. There is a method File.createWriteStream() which gets you a WritableStream to work with. There is also File.save() which accepts multiple kinds of things, including a Buffer. There are examples of using each method here.

like image 56
Doug Stevenson Avatar answered Oct 14 '22 13:10

Doug Stevenson