【问题标题】:How to upload file (selected by user) to Firebase Storage using node.js?如何使用 node.js 将文件(由用户选择)上传到 Firebase 存储?
【发布时间】:2021-07-17 14:59:00
【问题描述】:

我正在开发一个需要以下功能的项目(Web、node.js、Firebase 函数、托管和存储):

  • 用户通过选择文件
                    <input type="file" multiple>
  • 其他按钮运行旨在将选定文件上传到存储的脚本。

问题是 - 根据带有 node.js 的谷歌存储管理员的documentation,文件只能使用路径上传,例如:

const options = {
  destination: bucket.file('existing-file.png'),
  resumable: false
};

bucket.upload('local-img.png', options, function(err, newFile) {
  // Your bucket now contains:
  // - "existing-file.png" (with the contents of `local-img.png')

}); 

BUT 文件输入字段不允许让浏览器知道确切的路径是什么。 它让我知道:

  • 文件名
  • 文件 URL (URL.createObjectURL(...) -» "blob:https://mis...")
  • 文件本身是一个 blob

总结页面不能交出上传机制可以处理的变体。

有人知道怎么做吗?

谷歌函数调用:


var imageSelected = document.getElementById("imageSelected");
      var imageList = imageSelected.files;
      var imagePath = imageList.webkitRelativePath;

      for (var i = 0; i < imageList.length; i++) {
        imageFile = imageList[i];
        imageFileURL = URL.createObjectURL(imageFile).toString();
    
        var imageUpload = firebase.functions().httpsCallable('imageUpload');
        imageUpload({ file: imageFile, fileName: imageFile.name, filePath: imageFileURL });
        URL.revokeObjectURL(imageFileURL)
      }        

功能:

exports.imageUpload = functions.https.onCall((data, context) => {

    const storage = new Storage();
    var filePath = data.filePath;
    var fileName = data.fileName;
    var file = data.file;

    const options = {
        destination: bucket.file('TEST/' + fileName),
        resumable: false
    };

    return new Promise((Resolve, Reject) => {
        async function uploadFile() {
            storage
                .bucket("..............appspot.com")
                .upload(file, options);
            Resolve(fileName);
        }

        uploadFile().catch(error => {
            Reject(error);
        });
    });
});

【问题讨论】:

  • 流程是否类似于,首先用户从浏览器上传,然后服务器将其上传到谷歌云?
  • 不,用户只能通过输入框选择文件: 然后应该直接点击按钮上传。
  • 但是您使用 Cloud Functions 作为中间人对吗?您不能直接上传到 Google Cloud Storage,因为如果您在客户端使用它们可能会泄露 API 密钥。
  • 对不起,你是对的。
  • 您能否分享您实际调用 Cloud Functions 的代码以及在您的前端“上传”文件的代码?

标签: node.js firebase web google-cloud-functions firebase-storage


【解决方案1】:

这里的问题是您正在尝试使用云函数上传文件,就好像云函数可以访问本地文件系统中的文件一样,而它并没有在服务器端。

您需要做的是将文件base64编码为字符串,并将该字符串放入JSON有效负载中,然后在函数中对其进行解码,以便上传文件。请注意,这仅建议用于小文件。

如果您需要为更大的文件执行此操作,更好的选择是在您的客户端中执行上传,然后使用客户端 SDK 而不是管理 SDK 访问您的本地文件系统。

【讨论】:

  • 感谢您的回复。问题是这些文件不小于 200-300 kB,所以我想这些还不够小。另一件事是 Cloud Storage 不适用于 node.js:firebase.google.com/docs/web/setup 所以 ref.put() 不起作用:firebase.google.com/docs/storage/web/upload-files#web-v8_7 还有其他想法吗?
  • 好吧,因为它们不够小,你可以按照我在答案中所说的那样做,让客户端直接使用客户端 SDK 上传,它在 node.js 中可用,你可以找到文档它here.
猜你喜欢
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 2019-09-06
  • 2020-04-08
  • 2019-12-12
  • 2020-05-07
  • 1970-01-01
  • 2016-10-04
相关资源
最近更新 更多