How to upload a file using jQuery.ajax and FormData How to upload a file using jQuery.ajax and FormData ajax ajax

How to upload a file using jQuery.ajax and FormData


You have to add processData:false,contentType:false to your method, so that jQuery does not alter the headers or data (which breaks your current code).

function uploadFile(blobFile, fileName) {    var fd = new FormData();    fd.append("fileToUpload", blobFile);    $.ajax({       url: "upload.php",       type: "POST",       data: fd,       processData: false,       contentType: false,       success: function(response) {           // .. do something       },       error: function(jqXHR, textStatus, errorMessage) {           console.log(errorMessage); // Optional       }    });}  


If you are uploading from a HTML5 form that includes an input fo type file you can just use querySelector and FormData and it works.

In case of php it will give you all files in the $_FILE and all other inputs in the $_POST array.

JS/jQuery:

function safeFormWithFile(){  var fd = new FormData(document.querySelector('#myFormName'));  $.ajax({        url:'/catchFormData.php',        method:'POST',        data:fd,        processData: false,        contentType: false,        success:function(data){          console.log(data);        }  });}

HTML:

<form id="myFormName">  <input id="myImage" name="myImage" type="file">  <input id="myCaption" name="myCaption" type="text"></form>