Where developers come to connect, share, build and be inspired.

24

File uploads with jQuery HTML5 and FormData

4100 views

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!

Comments

  • A3c2604a955db2956ce923fb04da2dbe_normal
    bdgeeksfoysal

    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?

  • My_avatar_normal
    prudnikov

    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.

  • Ich
    shupal

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

Add a comment