Prakhar Prateek Prakhar Prateek - 3 months ago 19
Ajax Question

How to send image and data as two different parameters through ajax call?

var data = new FormData()
jQuery.each(jQuery('#file')[0].files, function(i, file){
data.append('file-'+i, file)
})
$.ajax({
method : 'post',
url : SERVER,
processData : false,
contentType : false,
//async : false,
data : { id: "2458" , file : data },
success : function(response){
if(response.success==1){
//do something
}
}
});


I need to upload an image to a third party api which accepts image file and id as parameter. However, whenever I am trying to use the above code, only image object is being sent. I need the id also to be sent. screenshot shows only image object being sent

Quick help will be appreciated.

Answer

Submitting multi part form for file upload

<form id="myForm" enctype="multipart/form-data">
    <input type="file" name="firstFile" id="file_1" data-filename="image.jpg">
    <input type="file" name="SecondFile" id="file_2" data-filename="image2.jpg">
    <button id="myFormButton">click</button>
</form>
var formData = new FormData();

$("#myFormButton").on("click", function (e) {
    e.preventDefault();
    var inputs = $("#myForm input");
    $.each(inputs, function (obj, v) {
        var file = v.files[0];
        var filename = $(v).attr("data-filename");
        var name = $(v).attr("id");
        formData.append(name, file, filename);
    });
    var xhr = new XMLHttpRequest;
    xhr.open('POST', 'your server URL', true);
    xhr.send(formData);
});