dsh*_*rew 15 javascript google-cloud-storage firebase google-cloud-functions
我有这个云功能,我写的上传文件到谷歌云存储:
const gcs = require('@google-cloud/storage')({keyFilename:'2fe4e3d2bfdc.json'});
var filePath = file.path + "/" + file.name;
return bucket.upload(filePath, {
destination: file.name
}).catch(reason => {
console.error(reason);
});
Run Code Online (Sandbox Code Playgroud)
我曾经formidable
解析上传的文件,我试图记录上传文件的属性,看起来很好; 它上传到临时目录'/tmp/upload_2866bbe4fdcc5beb30c06ae6c3f6b1aa/
但是当我尝试将文件上传到gcs时出现此错误:
{ Error: EACCES: permission denied, stat '/tmp/upload_2866bbe4fdcc5beb30c06ae6c3f6b1aa/thumb_ttttttt.jpg'
at Error (native)
errno: -13,
code: 'EACCES',
syscall: 'stat',
path: '/tmp/upload_2866bbe4fdcc5beb30c06ae6c3f6b1aa/thumb_ttttttt.jpg' }
Run Code Online (Sandbox Code Playgroud)
我使用这个html表单上传文件:
<!DOCTYPE html>
<html>
<body>
<form action="https://us-central1-appname.cloudfunctions.net/uploadFile" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
dsh*_*rew 15
我从Firebase支持团队获得了解决方案
首先,代码包含对"强大"库的一个小误解.这条线:
var filePath = file.path + "/" + file.name;
Run Code Online (Sandbox Code Playgroud)
表示我们期望'formidable'使用其原始名称上传我们的文件,并将其存储在具有随机名称的临时目录中.实际上,'强大'的作用是将文件上传到存储在'file.path'中的随机路径,而不再使用原始文件名.如果我们想要,我们可以通过阅读'file.name'找出原始文件名是什么.
因此,代码的快速修复更改:
var filePath = file.path + "/" + file.name;
Run Code Online (Sandbox Code Playgroud)
只是:
var filePath = file.path;
Run Code Online (Sandbox Code Playgroud)
其次,还有一个问题会导致代码出现问题:函数在'form.parse(...)'完成异步工作之前终止.这意味着实际的文件上传可能会在函数已经完成时发生,因此它不再保留任何CPU或内存 - 上传速度会非常慢,甚至可能会失败.
解决这个问题的方法是包含form.parse(...)
一个承诺:
exports.uploadFile = functions.https.onRequest((req, res) => {
var form = new formidable.IncomingForm();
return new Promise((resolve, reject) => {
form.parse(req, function(err, fields, files) {
var file = files.fileToUpload;
if(!file){
reject("no file to upload, please choose a file.");
return;
}
console.info("about to upload file as a json: " + file.type);
var filePath = file.path;
console.log('File path: ' + filePath);
var bucket = gcs.bucket('bucket-name');
return bucket.upload(filePath, {
destination: file.name
}).then(() => {
resolve(); // Whole thing completed successfully.
}).catch((err) => {
reject('Failed to upload: ' + JSON.stringify(err));
});
});
}).then(() => {
res.status(200).send('Yay!');
return null
}).catch(err => {
console.error('Error while parsing form: ' + err);
res.status(500).send('Error while parsing form: ' + err);
});
});
Run Code Online (Sandbox Code Playgroud)
最后,您可能需要考虑使用Cloud Storage for Firebase上传文件而不是云功能.Cloud Storage for Firebase允许您直接上传文件,并且可以更好地工作:
它具有访问控制
它具有可恢复的上传/下载(非常适合连接不良)
它可以接受任何大小的文件而不会出现超时问题
如果云功能应该运行以响应文件上传,你可以做更多
归档时间: |
|
查看次数: |
11340 次 |
最近记录: |