Manually uploading files via AJAX

Updated . Posted . Visible to the public.

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

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

var form = document.querySelector('form.my-form') // 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', 'foo@bar.com');
formData.append('attachment', attachment, 'filename.jpg');

You can now send your FormData via AJAX like this:

var request = new XMLHttpRequest();
request.open('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.

Henning Koch
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-03-29 07:37)