【问题标题】:Upload File to Firebase Storage using Admin SDK使用 Admin SDK 将文件上传到 Firebase 存储
【发布时间】:2019-08-02 07:51:12
【问题描述】:

根据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
}

【问题讨论】:

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


    【解决方案1】:

    由于 Firebase Admin SDK 只是封装了 Cloud SDK,您可以使用 Cloud Storage node.js API documentation 作为参考,看看它可以做什么。

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

    【讨论】:

      【解决方案2】:

      你应该做的是使用内置函数

      假设您在客户端以 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',
           },
      });
      

      【讨论】:

      • 我试过这样做,但我收到错误Error: ENOENT: no such file or directory, stat 'E:\Server\blob:http:\localhost:3000\34544810-4aa6-4070-adf8-15c636b92c29'还有其他方法吗?
      猜你喜欢
      • 2020-11-21
      • 2020-05-09
      • 2021-07-30
      • 2021-04-05
      • 1970-01-01
      • 2020-05-07
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多