Reputation: 53
I have a form where a user can upload a file:
<form enctype="multipart/form-data method="POST" id="cool-form-id">
<input type="file" id="file" name="file">
</form>
I'm trying to upload the file from this form using an AJAX request:
$.ajax({
url: '/path/to/upload/',
data: $("#cool-form-id").serialize(),
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
alert(data)
}
});
If I inspect the object obtained by the $("#cool-form-id") selector, I see the form & input field where someone has chosen a file, but after serialize() this input is gone (other input fields in this form are serialized as expected.)
var formData = new FormData($("#cool-form-id")[0]);
$.ajax({
url: '/path/to/upload/',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
alert(data)
}
});
I was able to solve this problem by instead using a FormData object to pass along the form information (seen above) but I'm having trouble figuring out why my original plan did not work (it is my understanding that FormData just creates a series of key/value pairs).
Most questions referencing FormData are not current and many just provide a working example.
I am curious if anyone could shed some light on any or all of the following:
1) Why can you not serialize() the form data for an input of type "file"?
2) What does FormData do differently that causes it to work in this scenario?
3) Is FormData still the only/best option for you to upload a file (assuming you don't want to use an iFrame)?
Upvotes: 5
Views: 982
Reputation: 944157
Why should FormData be used when uploading a file via AJAX?
Because you can't do it any other way (other than the iframe hack)
1) Why can you not serialize() the form data for an input of type "file"?
Because:
value
of a file input doesn't give the file contentserialize
could be rewritten to, for example, use the FileList API to read the files and then base64 encode them into a application/x-www-form-urlencoded string (it could but jQuery haven't done that) and then any server-side code that reads the data would have to decode the base64 data.
2) What does FormData do differently that causes it to work in this scenario?
It creates a multipart/form-data formatted body and reads files from file inputs.
3) Is FormData still the only/best option for you to upload a file (assuming you don't want to use an iFrame)?
It's the only sensible option.
Upvotes: 8