Prakhar Prateek Prakhar Prateek - 1 year ago 65
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)
method : 'post',
url : SERVER,
processData : false,
contentType : false,
//async : false,
data : { id: "2458" , file : data },
success : function(response){
//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 Source

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>
var formData = new FormData();

$("#myFormButton").on("click", function (e) {
    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;'POST', 'your server URL', true);