node.js - 如何使用 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')
});
但是不允许文件输入字段让浏览器知道确切的路径是什么。它让我知道:
- 文件名
- 文件 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);
});
});
});
解决方案
这里的问题是您正在尝试使用云函数上传文件,就好像云函数可以访问您本地文件系统中的文件一样,它不在服务器端。
您需要做的是将文件base64编码为字符串,并将该字符串放入JSON有效负载中,然后在函数中对其进行解码,以便可以上传文件。请注意,这只建议用于小文件。
如果您需要为更大的文件执行此操作,则更好的选择是在您的客户端中执行上传,然后使用客户端 SDK 而不是管理 SDK 访问您的本地文件系统。
推荐阅读
- php - 防止从外部目录包含 PHP 文件
- javascript - 由于错误 TypeError 未发送通知:无法读取 null 的属性“描述”
- types - 记录判别式能否在 Ada 中间接确定数组长度?
- python - 在分布式张量流中涉及实例梯度时性能缓慢
- python - 无法从购物车中删除商品
- jsp - 如何对 jsp 页面和 wsdl 进行 OPTIONS Rest 调用
- postgresql - Postgres:如何优化使用多个 json_array_elements() 调用的查询
- r - R通过索引列表调用一组列
- postgresql - 第一次尝试使用 Docker:来自守护进程的错误响应:驱动程序在端点网络服务器上编程外部连接失败(2d9
- linux - 如何避免 Windows 上 Git/IntelliJ 文件中的 CR?