File uploads with jQuery HTML5 and FormData
Before HTML5 there were a bunch of techniques and plugins for jQuery to implement AJAX file uploads. HTML5 introduces FormData class that can simplify file uploads.
$('#myform').on('sumbit', function(){
var form = $(this);
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : '/upload',
data : formdata ? formdata : form.serialize(),
cache : false,
contentType : false,
processData : false,
type : 'POST',
success : function(data, textStatus, jqXHR){
// Callback code
}
});
});
Thant's it. You fon't need any plugins, flash or iframe tricks. It just works. There is a couple tricks here that makes this code to work the way we expect:
- When we create instance of FormData we pass form[0] instead form. It's mean actual form element, but not jQuery selector.
- Instead of defining
contentType
we just passfalse
. This tells jQuery to not addContent-Type
header to the request. - We set
processData
tofalse
, so, jQuery will not convert ourdata
value (which in stance ofFormData
) to a string.
There is very helpful HTML5Rocks article
Happy coding!
Related protips:
Written by Vladimir Prudnikov
Related protips
8 Responses
Wow! That looks neat. Never knew it could be this simple. I've been using jQuery plugins like dragonfly, uploadify etc. for ajax file upload which are really messy comparing to this. But there must be browser dependency issue with this right? I mean ie fallback etc. can cause problems while using this method?
I did not tested on many browsers, I needed this for our internal tool. Form data has support in all modern browsers including IE 10+. Also take a look at Modernizr and HTML5Shim.
have you tested it on mobile browser or platforms? Because the behaviour from anroid and iOS are sometimes really different.
Very Good! works perfect!
ie11 doesn't upload and firefox 5 or something like that .. i just tested it right now. it was a simple and clean solution yet the problems.. :-( just made go crazy
I tried using Formdata, but it seems to fail for large file size, I get a 500 error..
There's a typo here $('#myform').on('sumbit' ... the event name should be "submit".
I like the simplicity of this approach. Thanks *