O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Uploading Files

Part of the XMLHttpRequest Level 2 specification was the ability to upload files. File uploads have long been a painful experience for users. Once they’ve browsed and selected a file, the page reloads and they have to wait for ages while it uploads, with no indication of progress or feedback—quite the usability nightmare. Luckily for us, XHR 2 solves this problem. It allows us to upload files in the background, and it even gives us progress events so that we can provide the user with a real-time progress bar. It’s generally well supported by the major browsers:

  • Safari >= 5.0

  • Firefox >= 4.0

  • Chrome >= 7.0

  • IE: no support

  • Opera: no support

File uploads can be done via the existing XMLHttpRequest API, using the send() function, or alternatively by using a FormData instance. A FormData instance just represents the contents of a form in an easy-to-manipulate interface. You can build a FormData object from scratch, or by passing in an existing form element when instantiating the object:

var formData = new FormData($("form")[0]);

// You can add form data as strings
formData.append("stringKey", "stringData");

// And even add File objects
formData.append("fileKey", file);

Once you’ve finished with the FormData, you can POST it to your server using XMLHttpRequest. If you’re using jQuery for Ajax requests, you’ll need to set the processData option to false so that jQuery doesn’t try to serialize the supplied data. Don’t set the Content-Type header because the browser will set it automatically ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required