【问题标题】:Uploading files and JSON data in the same request express node js在同一请求中上传文件和JSON数据表达节点js
【发布时间】:2017-02-28 16:33:23
【问题描述】:

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

尝试的选项:

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

【问题讨论】:

  • 你找到解决方案了吗?

标签: node.js express pug


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2016-01-15
    • 2019-03-19
    • 2016-10-12
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多