p-n7eq
22.14K
· February 2013 ·

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 pass false. This tells jQuery to not add Content-Type header to the request.
  • We set processData to false, so, jQuery will not convert our data value (which in stance of FormData) to a string.

There is very helpful HTML5Rocks article

Happy coding!

Sign in or sign up to add your response.

5 Responses

3703

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?

over 1 year ago ·
3713

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.

over 1 year ago ·
3727
Shupal

have you tested it on mobile browser or platforms? Because the behaviour from anroid and iOS are sometimes really different.

over 1 year ago ·
18175
None

Very Good! works perfect!

over 1 year ago ·
20923
None

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

over 1 year ago ·