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:
-
FormData
is available in Internet Explorer 10+ Show archive.org snapshot . - While there are
various
Show archive.org snapshot
polyfills
Show archive.org snapshot
for
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. - There are solutions like
jQuery file upload
Show archive.org snapshot
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.
Posted by Henning Koch to makandra dev (2016-03-29 07:37)