如何使用Cloud功能上的Express for Firebase(multer,busboy)

我试图将文件上传到Cloud Functions,使用Express处理那里的请求,但是我没有成功。我创建了一个在本地工作的版本:


服务器端js


const express = require('express');

const cors = require('cors');

const fileUpload = require('express-fileupload');


const app = express();

app.use(fileUpload());

app.use(cors());


app.post('/upload', (req, res) => {

    res.send('files: ' + Object.keys(req.files).join(', '));

});

客户端js


const formData = new FormData();

Array.from(this.$refs.fileSelect.files).forEach((file, index) => {

    formData.append('sample' + index, file, 'sample');

});


axios.post(

    url,

    formData, 

    {

        headers: { 'Content-Type': 'multipart/form-data' },

    }

);

当部署到未定义req.files的Cloud Functions时,此完全相同的代码似乎会中断。有人知道这里发生了什么吗?


编辑 我也可以使用using multer,它在本地工作得很好,但是一旦上传到Cloud Functions,这给了我一个空数组(相同的客户端代码):


const app = express();

const upload = multer();

app.use(cors());


app.post('/upload', upload.any(), (req, res) => {

    res.send(JSON.stringify(req.files));

});


叮当猫咪
浏览 360回答 3
3回答

冉冉说

在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应用程序不同的所有情况。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript