I have a simple form for uploading a file that works well enough synchronously:
<form id="uploadForm" action="/upload" method="post" encType="multipart/form-data">
<input type="file" id="file" name="file" accept=".csv" />
<input type="text" name="comment" />
<button type="submit">Upload</button>
</form>
How can I make this form upload the file asynchronously (without reloading the page?), and be notified when the upload is complete, and if there were any errors?
I know that the primary way to make an asynchronous request is to use an XMLHttpRequest
, and I see that something like the following is now possible (I have not tested this code):
function handleLoad() {
console.log(this.responseText);
}
function handleError(error) {
console.error(error.stack);
}
function handleSubmit(e) {
e.preventDefault();
var form = document.getElementById('uploadForm');
var request = new XMLHttpRequest();
request.addEventListener('load', handleLoad);
request.addEventListener('error', handleError);
request.open("POST", "/upload");
request.send(new FormData(form));
}
However, according to MDN, sending FormData
, Blob
s, File
s, or ArrayBuffer
s is only supported in IE10+, and I want a backwards-compatible solution (which doesn't use jQuery).
There are plenty of answers to How can I upload files asynchronously?, but all of the answers I have read so far use jQuery or use the modern XMLHttpRequest method I described above.
I am using React and have no use for anything else jQuery offers, so I would like to keep my page download size smaller by solving this with vanilla JS.