Posted over 1 year ago. Visible to the public.

Manually uploading files via AJAX

To upload a file via AJAX (e.g. from an <input type='file'>) you need to wrap your params in a FormData object.

You can initialize a FormData using the contents of a form:

var form = document.querySelector('') // Find the <form> element var formData = new FormData(form); // Wrap form contents

Or you can construct it manually, param by param:

var fileInput = document.querySelector('form input[type=file]'); var attachment = fileInput.files[0]; var formData = new FormData(); formData.append('email', ''); formData.append('attachment', attachment, 'filename.jpg');

You can now send your FormData via AJAX like this:

var request = new XMLHttpRequest();'POST', '/my/url', true); request.onload = function() { console.log("Server responded with %o", request.responseText) }; request.send(formData);

In jQuery you would send it like this:

$.ajax({ url: '/my/url', type: 'POST', data: formData, contentType: false, processData: false });

Note the contentType and processData options, which are needed so that jQuery does not try to serialize the FormData object.

Supporting legacy browsers

Short story:

  • The solution above works in IE 10
  • I recommend to offer a standard, non-AJAX form for older IEs
  • All other solutions will bring you pain and long nights

Long story:

  • FormData is available in Internet Explorer 10+.
  • While there are various polyfills for FormData, they're kind of pointless for our purpose. To be able to serialize files, they all require the File API, which again is available in Internet Explorer 10+ only.
  • There are solutions like jQuery file upload that promise to work in legacy browsers. They mostly work by making a vanilla form submission to a hidden <iframe> and try to wrap a nice Javascript API around this. I found it really hard to make this work reliably.

Also see Dynamically uploading files to Rails with jQuery File Upload.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Author of this card:

Henning Koch
Last edit:
about 1 year ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandropedia