Firebase:使用带字段的快递上传多部分/表单

时间:2018-02-01 06:10:27

标签: javascript firebase express google-cloud-functions google-cloud-firestore

我正在使用https://stackoverflow.com/a/47603055/160059中的解决方案 - 如何使用Express for Firebase执行HTTP文件上传

它会抛出错误:

{
 "error": {
    "code": 500,
    "status": "INTERNAL",
    "message": "function crashed",
    "errors": [
        "socket hang up"
    ]
  }
}

当multipart / form还有" not file"领域。 我希望在我的req中同时拥有文件和正文,这样我就可以在一个函数中更新我的firestore和firebase存储。

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use((req, res, next) => {
    if(req.rawBody === undefined && req.method === 'POST' && req.headers['content-type'].startsWith('multipart/form-data')){
        getRawBody(req, {
            length: req.headers['content-length'],
            limit: '10mb',
            encoding: contentType.parse(req).parameters.charset
        }, function(err, string){
            if (err) return next(err)
            req.rawBody = string
            next()
        })
    } else {
    next()
    }
})

app.use((req, res, next) => {
    if (req.method === 'POST' && req.headers['content-type'].startsWith('multipart/form-data')) {
        const busboy = new Busboy({ headers: req.headers })
        let fileBuffer = new Buffer('')
        req.files = []


        busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
            file.on('data', (data) => {
                fileBuffer = Buffer.concat([fileBuffer, data])
            })

            file.on('end', () => {
                const file_object = {
                    fieldname,
                    'originalname': filename,
                    encoding,
                    mimetype,
                    buffer: fileBuffer
                }

                req.files.push(file_object)
                next()
            })
        })

        busboy.end(req.rawBody)
    } else {
        next()
    }
})

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

  let promise = req.files.map((file, index) => {
    return bucket.upload(file);
  });

  Promise.all(promise).then(()=> {
    admin.firestore()
     .collection("data")
     .doc().set({data: req.body});
  }).catch((err)=>{console.log(err)})
  res.send("files: " + JSON.stringify(req.files) + "body: " + JSON.stringify(req.body));

});

0 个答案:

没有答案