I tried to send a file using an Ajax POST request using two methods:
Method 1 (jQuery val()) –
JavaScript
x
21
21
1
$.ajax({
2
url: 'somewhere',
3
method: 'post',
4
processData: true,
5
contentType: true,
6
7
data:{
8
'data1': $('#fileinputid').val(), // File input
9
}
10
11
success:function(){
12
// Do something;
13
}
14
15
error:function(){
16
// Do something;
17
},
18
19
});
20
21
Method 2- (FormData)
JavaScript
1
21
21
1
var formData = new FormData(document.getElementById("form-id"));
2
3
$.ajax({
4
url: 'somewhere',
5
method:'post',
6
cache: false,
7
processData:false,
8
contentType: false,
9
10
data: formData,
11
12
success: function(){
13
// Do something for success
14
},
15
16
error: function(){
17
// Do something for error
18
},
19
20
});
21
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.