Multipart/form-data with arrays

三世轮回 提交于 2019-12-04 09:38:57

问题


I have a simple form:

<form method="post" action="/test">
  <input type="hidden" name="arr[]" value="val1">
  <input type="hidden" name="arr[]" value="val2">
  <input type="hidden" name="arr[]" value="val3">
  <input type="submit" value="Submit">
</form>

With the controller:

//...
server.post('/test', function(req, res) {
    res.json(req.body);
});
//...

This returns fine with:

{
  arr: [
    "val1",
    "val2",
    "val3"
  ]
}

However, when I change the enctype to multipart/formdata

<form method="post" action="/test" enctype="multipart/form-data">
  <input type="hidden" name="arr[]" value="val1">
  <input type="hidden" name="arr[]" value="val2">
  <input type="hidden" name="arr[]" value="val3">
  <input type="submit" value="Submit">
</form>

The server now responds with:

{
  arr[]: "val3"
}

What's the issue? Is there some kind of configuration I need?

In case you're wondering, I'm also sending a file, that why I need the multipart/form-data.


回答1:


It's probably related to the use of body-parser (especially the urlencoded method) which, by default, works on requests with the media-type application/x-www-form-urlencoded only.

Your main application module probably has some lines like these:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());

I suppose, you could just add the following to have requests of type multipart/form-data parsed as well:

app.use(bodyParser.urlencoded({
  type: 'multipart/form-data'
}));


来源:https://stackoverflow.com/questions/23674208/multipart-form-data-with-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!