2016-10-27 65 views
2

我在使用enctype multipart/form-data和發送具有相同名稱的輸入作爲數組時獲得一些麻煩。我只能似乎獲得上傳圖像或陣列的輸入,但不能兩者都在同一時間...NodeJS與數組的多部分/表格數據

例如,我有這樣的形式:

<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"> 

我最終接受了「FileAttachment的」只是在我的應用程序的NodeJS罰款,但我只獲得最後值「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] 
    } 
} 

如果未設置的加密類型,在「testinput」數據來作爲一個數組,但「FileAttachment的」丟失,我只得到了上傳的文件名,如:

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

我認爲這與我設置快速「body parser」的方式有關,但我似乎無法弄清楚正確的配置。這是我的設置(簡化了相關的代碼):

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 with arrays,但它是2歲,未答覆,似乎並沒有使用依賴fileUpload

而且,我試圖回答這個問題Handling input arrays in Express forms?提出的方法,但我不斷收到對服務器看起來是文字而不是陣列,像這樣:

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

我缺少什麼?我應該嘗試什麼?

回答

0

我能夠通過從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 
     } 
    ] 
} 

正如你可以看到輸入陣列上捆綁在一起,文件似乎是正確收到。