Last Updated: June 27, 2023
·
134.8K
· prudnikov

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!

Related protips:

fatal: refusing to merge unrelated histories

8 Responses
Add your response

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 ·

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 ·

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

over 1 year ago ·

Very Good! works perfect!

over 1 year ago ·

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 ·

I tried using Formdata, but it seems to fail for large file size, I get a 500 error..

over 1 year ago ·

There's a typo here $('#myform').on('sumbit' ... the event name should be "submit".

over 1 year ago ·

I like the simplicity of this approach. Thanks *

over 1 year ago ·