0

How can someone send json object and input file on the same request. I am familiar with this post and others.I don't use a <form> element as a parent of the <input type="file"> element but just a div. My code is like this:

var inputFiles = document.getElementById('archiveFile').files[0]
var formData = new FormData(); // Currently empty
formData.append('file[]',inputFiles,'hey.png')//append the input file



var data= { p_doc_no: "some value",
            p_receive_date: "some value1",
            p_thema: "some value2",
            p_prot_no: "some value3",
            p_sender: "some value4",
            p_energeia: "some value5",
        }

I have tried appending the object in the formData like this:

for ( var key in data ) {
    formData.append(key, data[key]);
}

and then make the AJAX request like this:

$.ajax({
    url: 'makeDBEntry/archive',
    data: formData,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});

but no luck until now. Any thoughts? At the end i need to access the request data from node js

Update Thanks to charlietfl I have found my silly solution as easy as using the multer module to handle formdata in node js

5
  • 1
    Your client side approach seems fine. Problem is likely server side assuming url path is correct, input id is correct etc. What errors are you getting from the ajax and in your node console? Commented Feb 11, 2017 at 20:34
  • 1
    my req.body property is empty and also when i try to save the file with the multer module the req.fiiles is also undefined would you like to upload the server side? Commented Feb 11, 2017 at 20:34
  • 1
    are you using correct body parser? Have you tried this using a simple form and no ajax? Commented Feb 11, 2017 at 20:35
  • 1
    I am usin JSON .. Commented Feb 11, 2017 at 20:36
  • 1
    but you aren't sending json, you are sending formData Commented Feb 11, 2017 at 20:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.