使用Admin SDK将文件上传到Firebase存储

时间:2019-03-11 22:27:55

标签: node.js firebase express google-cloud-storage firebase-admin

根据Docs,我必须将文件名传递给函数才能上传文件。

// 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',
  },
});

我在服务器端代码中使用Firebase Admin SDK(Nodejs),并且客户端以表单数据形式发送文件,我将其作为文件对象获得。当函数仅接受导致文件路径的文件名时,该如何上传?

我希望能够做这样的事情


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

2 个答案:

答案 0 :(得分:0)

由于Firebase Admin SDK仅包装了Cloud SDK,因此您可以使用Cloud Storage node.js API documentation作为参考来查看其功能。

您不必提供本地文件。您也可以使用节点流上传。有一种方法File.createWriteStream()使您可以使用WritableStream。还有File.save()可以接受多种内容,包括缓冲区。有使用每种方法here的示例。

答案 1 :(得分:0)

您应该做的就是使用内置功能

假设您在客户端以imageDoc的形式接收文件,并且

 const imageDoc = e.target.files[0]

在节点中,您现在可以获得对象的URL路径

 const imageDocUrl = URL.createObjectURL(imageDoc)

所以您的最终代码将是

 // Uploads a local file to the bucket
    await storage.bucket(bucketName).upload(imageDocUrl, {
         // 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',
     },
});