Uploading files and JSON data in the same request express node js
Asked Answered
V

1

11

I have the below form written in 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>

I want this form to post data of files and other arrays as JSON object in Express.js

My 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" }));

My index.js

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

});

Output received is:

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

Expected output is to receive JSON data as shown above and to receive all the file data with filename, tmpname etc to save the file in a directory. Currently I am only getting the file name.

Options tried:

If I use multer and/or change the form enctype="multipart/form-data" than it does not pass my JSON data in object form rather it consider it as string.

Vulgate answered 19/10, 2016 at 7:11 Comment(1)
did you get solution?Ming
P
8

Is not intended to combine multiple content types on the same request, if you send an application/json content type the server will expect all the data to be in that format. So, the file content will not be processed by the parser. One option is to use multipart/form-data and send your JSON data as string, and then, using JSON.parse(), convert it to JSON in the server. Another option is to separate your file upload in another route. And send two separated requests for this purpose.

Placate answered 8/8, 2018 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.