【发布时间】:2018-07-12 03:47:28
【问题描述】:
我正在尝试使用 Google Cloud Function 处理文件上传。该函数使用 Busboy 解析多部分表单数据,然后上传到 Google Cloud Storage。
我一直收到同样的错误:ERROR: { Error: ENOENT: no such file or directory, open '/tmp/xxx.png' 触发函数时出错。
当 storage.bucket.upload(file) 尝试打开文件路径 /tmp/xxx.png 时,错误似乎发生在 finish 回调函数中。
请注意,我无法按照this question 中的建议生成签名上传 URL,因为调用它的应用程序是外部的非用户应用程序。我也不能直接上传到 GCS,因为我需要根据一些请求元数据制作自定义文件名。我应该改用 Google App Engine 吗?
功能代码:
const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
const Storage = require('@google-cloud/storage');
const _ = require('lodash');
const projectId = 'xxx';
const bucketName = 'xxx';
const storage = new Storage({
projectId: projectId,
});
exports.uploadFile = (req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
const uploads = []
const tmpdir = os.tmpdir();
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const filepath = path.join(tmpdir, filename)
var obj = {
path: filepath,
name: filename
}
uploads.push(obj);
var writeStream = fs.createWriteStream(obj.path);
file.pipe(writeStream);
});
busboy.on('finish', () => {
_.forEach(uploads, function(file) {
storage
.bucket(bucketName)
.upload(file.path, {name: file.name})
.then(() => {
console.log(`${file.name} uploaded to ${bucketName}.`);
})
.catch(err => {
console.error('ERROR:', err);
});
fs.unlinkSync(file.path);
})
res.end()
});
busboy.end(req.rawBody);
} else {
res.status(405).end();
}
}
【问题讨论】:
标签: javascript node.js google-cloud-storage google-cloud-functions busboy