Posted almost 6 years 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 Archive 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:

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

Flaky tests are tests that sometimes fail for no obvious reason. They are the plague of many end-to-end (E2E) test suites that automate the browser through tools like Capybara and Selenium.

Join our free training event and learn to fix any flaky test suite, even in large legacy applications.

Owner of this card:

Henning Koch
Last edit:
over 5 years 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 makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more