在同一请求中上传文件和JSON数据表示节点js

poo*_*lot 6 node.js express pug

我有以下用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>
Run Code Online (Sandbox Code Playgroud)

我希望这个表单在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" }));
Run Code Online (Sandbox Code Playgroud)

我的index.js

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

});
Run Code Online (Sandbox Code Playgroud)

收到的输出是:

body
  {
    finalchallan: 
    [
        { 
            unloadingDestination: 'sdcsdf',       
            CCNFForm: 'zsd',
            tollCopy:'abc.txt',      
        },
        { 
            unloadingDestination: 'sdcsdf',       
            CCNFForm: 'zsd',       
            tollCopy:'xyz.txt',
        }
    ],
    tollCopy: '' }
files
undefined
Run Code Online (Sandbox Code Playgroud)

预期的输出是接收如上所示的JSON数据,并接收带有filename,tmpname等的所有文件数据,以将文件保存在目录中.目前我只获取文件名.

尝试的选项:

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

Jua*_*mez 5

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