【发布时间】: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