3 回答

TA贡献1877条经验 获得超1个赞
在Cloud Functions设置中确实发生了重大更改,触发了此问题。它与中间件的工作方式有关,该中间件适用于用于服务HTTPS功能的所有Express应用程序(包括默认应用程序)。基本上,Cloud Functions将解析请求的主体并决定如何处理它,将主体的原始内容保留在中的Buffer中req.rawBody。您可以使用它直接解析多部分内容,但不能使用中间件(如multer)来实现。
相反,您可以使用称为busboy的模块直接处理原始内容。它可以接受rawBody缓冲区,并使用找到的文件回叫您。这是一些示例代码,这些代码将迭代所有上载的内容,将它们另存为文件,然后将其删除。您显然会想做些更有用的事情。
const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
exports.upload = functions.https.onRequest((req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
// This object will accumulate all the uploaded files, keyed by their name
const uploads = {}
// This callback will be invoked for each file uploaded
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log(`File [${fieldname}] filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);
// Note that os.tmpdir() is an in-memory file system, so should only
// be used for files small enough to fit in memory.
const filepath = path.join(os.tmpdir(), fieldname);
uploads[fieldname] = { file: filepath }
console.log(`Saving '${fieldname}' to ${filepath}`);
file.pipe(fs.createWriteStream(filepath));
});
// This callback will be invoked after all uploaded files are saved.
busboy.on('finish', () => {
for (const name in uploads) {
const upload = uploads[name];
const file = upload.file;
res.write(`${file}\n`);
fs.unlinkSync(file);
}
res.end();
});
// The raw bytes of the upload will be in req.rawBody. Send it to busboy, and get
// a callback when it's finished.
busboy.end(req.rawBody);
} else {
// Client error - only support POST
res.status(405).end();
}
})
请记住,保存到临时空间的文件会占用内存,因此它们的大小应限制为总共10MB。对于较大的文件,您应该将那些文件上传到Cloud Storage并使用存储触发器对其进行处理。
另外请记住,Cloud Functions添加的中间件的默认选择当前未通过添加到本地仿真器firebase serve。因此,在这种情况下,该示例将不起作用(rawBody将不可用)。
团队正在努力更新文档,以更清楚地了解HTTPS请求期间与标准Express应用程序不同的所有情况。
添加回答
举报