【发布时间】:2018-09-18 01:12:54
【问题描述】:
在 Node.js 和 Google 云上苦苦挣扎。我正在尝试将文件上传到 Google Cloud Storage 中的存储桶。基本上我在这个答案中使用代码:https://stackoverflow.com/a/45253054/324691,但我无法让它工作。这是我的代码:
const Storage = require('@google-cloud/storage');
const storage = new Storage();
var form = new formidable.IncomingForm();
// form.maxFieldsSize = 20 * 1024 * 1024; // default
form.maxFieldsSize = 20 * 1024;
// form.maxFileSize = 200 * 1024 * 1024;
// 4 MB / minute, 1 hour
form.maxFileSize = 4 * 60 * 1024 * 1024;
// Limit to 10 minutes during tests (4 MB/minute)
form.maxFileSize = 2 * 1024 * 1024;
form.maxFileSize = 4 * 10 * 1024 * 1024;
form.encoding = 'utf-8';
form.keepExtensions = true;
form.type = 'multipart';
return new Promise((resolve, reject) => {
form.parse(req, (err, fields, files) => {
console.warn("form.parse callback", err, fields, files);
if (err) {
reject(new Error(err));
return;
}
var file = files.upload;
if(!file){
reject(new Error("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);
console.log('File name: ' + file.name);
var bucket = storage.bucket(bucketName)
console.info("typeof bucket.upload", typeof bucket.upload);
bucket.upload(filePath, {
destination: file.name
}).then(() => {
resolve(true); // Whole thing completed successfully.
return true;
}).catch((err) => {
console.warn("catch bucket.upload, err", err);
reject(new Error('Failed to upload: ' + JSON.stringify(err)));
});
console.warn("After bucket.upload");
});
console.warn("After form.parse");
}).then(() => {
console.warn("form.parse then");
res.status(200).send('Yay!');
return true;
}).catch(err => {
console.warn("form.parse catch");
console.error('Error while parsing form: ' + err);
res.status(500).send('Error while parsing form: ' + err);
});
控制台日志中的输出看起来不错(包括 file.path 和 file.name),但是当它到达 bucket.upload(类型为 function)时,它会崩溃并出现错误 Error while parsing form: Error: Failed to upload: {"message":"Error during request."}。然后它说Execution took 1910 ms, user function completed successfully。在那之后终于Function worker killed by signal: SIGTERM。
我一直在使用 bucketName 进行测试,无论是否使用“gs://”。
我一直在测试不同的授权方式:
const storage = new Storage({ projectId: projectId });
const storage = new Storage({ keyFileName: 'path-to-keyfile.json'});
const storage = new Storage();
密钥文件是服务帐户的密钥文件(请参阅https://cloud.google.com/docs/authentication/getting-started)。
这是一个 Firebase 项目,我正在本地 Firebase 服务器 (firebase serve --only functions,hosting) 上进行测试。
这里有什么问题?
【问题讨论】:
标签: node.js firebase authorization google-cloud-storage