I tried to send a file using an Ajax POST request using two methods:
Method 1 (jQuery val()) –
$.ajax({ url: 'somewhere', method: 'post', processData: true, contentType: true, data:{ 'data1': $('#fileinputid').val(), // File input } success:function(){ // Do something; } error:function(){ // Do something; }, });
Method 2- (FormData)
var formData = new FormData(document.getElementById("form-id")); $.ajax({ url: 'somewhere', method:'post', cache: false, processData:false, contentType: false, data: formData, success: function(){ // Do something for success }, error: function(){ // Do something for error }, });
Now, Method 2 worked, but Method 1 did not. What is the reason for that?
Advertisement
Answer
$('#fileinputid').val()
only gets you the file name. You can not upload a file with that.
FormData
is capable of creating the whole multipart/formdata request structure that is needed for a file upload.