首页 > 解决方案 > 如何使用 node.js 将文件(由用户选择)上传到 Firebase 存储?

问题描述

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

                    <input type="file" multiple>

问题是 - 根据google storage admin with node.js 的文档,文件只能使用路径上传,例如:

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')

}); 

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

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

有谁知道如何做到这一点?

谷歌函数调用:


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);
        });
    });
});

标签: node.jsfirebasewebgoogle-cloud-functionsfirebase-storage

解决方案


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

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

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


推荐阅读