gpt4 book ai didi

node.js - 在同一个请求express node js中上传文件和JSON数据

转载 作者:搜寻专家 更新时间:2023-10-31 22:34:22 24 4
gpt4 key购买 nike

我有以下用 JADE 编写的表格

<form id="formAddchallandetails" action="/adddata" method="post" name="adduser">
<input id="inputunloadingDestination1" type="text" name="finalchallan[1][unloadingDestination]" placeholder="unloading Destination">
<input id="inputCCNFForm1" type="text" name="finalchallan[1][CCNFForm]" placeholder=" Challan Number">
<input id="inputtollCopy1" type="file" name="finalchallan[1][tollCopy]" >

<input id="inputunloadingDestination1" type="text" name="finalchallan[2][unloadingDestination]" placeholder="unloading Destination">
<input id="inputCCNFForm2" type="text" name="finalchallan[2][CCNFForm]" placeholder=" CCNF form">
<input id="inputtollCopy2" type="file" name="finalchallan[2][tollCopy]" >
<button id="btnSubmit" type="submit">submit</button>
</form>

我希望此表单在 Express.js 中将文件和其他数组的数据作为 JSON 对象发布

我的 app.js

    app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));//set to true for passing array objects from form to route
app.use(cookieParser());
app.use(bodyParser({ keepExtensions: true, uploadDir: "uploads" }));

我的 index.js

router.post('/adddata', function(req, res) {
console.log("body");
console.log(req.body);
console.log("files");
console.log(req.files);

});

收到的输出是:

body
{
finalchallan:
[
{
unloadingDestination: 'sdcsdf',
CCNFForm: 'zsd',
tollCopy:'abc.txt',
},
{
unloadingDestination: 'sdcsdf',
CCNFForm: 'zsd',
tollCopy:'xyz.txt',
}
],
tollCopy: '' }
files
undefined

预期输出是接收如上所示的 JSON 数据,并接收具有文件名、tmpname 等的所有文件数据,以将文件保存在目录中。目前我只得到文件名。

尝试过的选项:

如果我使用 multer 和/或更改表单 enctype="multipart/form-data" 它不会以对象形式传递我的 JSON 数据,而是考虑它作为字符串。

最佳答案

不打算在同一请求中组合多种内容类型,如果您发送 application/json 内容类型,服务器将期望所有数据都采用该格式。因此,解析器不会处理文件内容。一种选择是使用 multipart/form-data 并将您的 JSON 数据作为字符串发送,然后使用 JSON.parse() 在服务器中将其转换为 JSON。另一种选择是在另一条路径中分离文件上传。并为此发送两个单独的请求。

关于node.js - 在同一个请求express node js中上传文件和JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com