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



我用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>

我想这个表单发布文件和其他数组的数据作为JSON对象在Express.js

我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数据,并接收带有filename, tmpname等的所有文件数据,以将文件保存在目录中。目前我只得到文件名。

选择尝试:

如果我使用multer和/或改变形式enctype="multipart/form-data",它不会以对象形式传递我的JSON数据,而不是将其视为字符串。

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

最新更新