NodeJS Multipart / form-data与数组

我在使用enctype multipart/form-data和发送具有相同名称的input作为数组时遇到了一些麻烦。 我似乎只能得到一个上传的图像或arraysinput,但不能同时…

例如,我有这样的forms:

 <form method="post" action="/test"> <input name="testinput" value="valueA"> <input name="testinput" value="valueB"> <input type="file" name="fileattachment"> <input type="submit" value="Submit"> </form> 

如果我将表单的enctype设置为multipart/form-data ,如下所示:

 <form method="post" action="/test" enctype="multipart/form-data"> 

我最终在我的NodeJS应用程序中收到'fileattachment'就好了,但是我只获得'testinput'的最后一个值,就像这样:

 //req.body //--- { testinput: 'valueB' // I'm missing valueA! } //req.files //--- { fileattachment: { name: 'biglogo.png', data: <Buffer 89 ... >, encoding: '7bit', mimetype: 'image/png', mv: [Function] } } 

如果enctype没有设置,'testinput'数据是以数组forms出现的,但'fileattachment'丢失了,我只能得到上传文件的名字,如下所示:

 //req.body //--- { testinput: ['valueA', 'valueB'], fileattachment: 'some_picture.png' // Useless for file uploading } 

我认为这与我设置快速“body parser”的方式有关,但我似乎无法弄清楚正确的configuration。 这是我的设置(简化了相关的代码):

 var express = require('express'); var fileUpload = require('express-fileupload'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use(fileUpload()); // Must be placed after, not before, bodyparser's use, otherwise files fail to be uploaded correctly... app.post('/test', function(req, res) { // Some code }); 

另外,这是我的package.json文件:

 { "name": "my-app", ... "dependencies": { "body-parser": "~1.15", "express": "~4.14", "express-fileupload": "^0.0.5" } } 

这在node/6.9.1上运行

我已经看到这个非常类似的问题与数组Multipart / form-data ,但它是2岁,没有答案,似乎并没有使用依赖fileUpload

另外,我尝试了这个问题的答案提出的方法在Express表单处理input数组? ,但我一直在服务器上看起来是文本而不是数组,如下所示:

 { 'something[0][testinput]': 'valueA', 'something[1][testinput]': 'valueB' } 

我错过了什么? 我应该尝试什么?

我能够通过从express-fileupload切换到Multiparty来获得所需的结果

设置:

 var express = require('express'); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); 

我的代码:

 var multiparty = require('multiparty'); app.post('/test', function(req, res) { (new multiparty.Form()).parse(req, function(err, fields, files) { // handling fields and files code }); }); 

领域:

 { testinput: ['valueA', 'valueB'] } 

文件:

 { fileattachment: [ { fieldName: 'fileattachment', originalFilename: 'biglogo.png', path: '/tmp/blablaasdfgh.png', headers: [Object], size: 10130 } ] } 

正如你所看到的那样,input是捆绑在一个数组上的,这个文件看起来是正确的。