Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 723
poojasalot Avatar asked Oct 19 '16 07:10

poojasalot


1 Answers

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.

like image 147
Juan D. Gómez Avatar answered Sep 17 '22 15:09

Juan D. Gómez