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.
Short story:
Long story:
FormData
is available in Internet Explorer 10+
Show archive.org snapshot
.FormData
, they're kind of pointless for our purpose. To be able to serialize files, they all require the
File API
Show archive.org snapshot
, which again is available in Internet Explorer 10+ only.<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.