Motivation
We're currently on our way to implement a webcomponent that handles file uploads. These could also be larger files like recorded videos.
What I've checked
From what I've researched so far, we can either go with the File API, or with the fetch API
.
The File API looks to be designed to be used in conjunction with XMLHttpRequest
objects:
This API is designed to be used in conjunction with other APIs and elements on the web platform, notably:
XMLHttpRequest
(e.g. with an overloadedsend()
method forFile
orBlob
arguments),postMessage()
,DataTransfer
(part of the drag and drop API defined in HTML) and Web Workers.
Tbf, for all other use cases of server communication we have replaced XMLHttpRequest
s with the much simpler fetch API
.
Question
Using the XMLHttpRequest
way, you have access to a progress
hook which would allow informing the user about how far their upload has progressed, like e.g. showing a percentage uploaded, as shown on MDN:
function FileUpload(img, file) {
const reader = new FileReader();
this.ctrl = createThrobber(img);
const xhr = new XMLHttpRequest();
this.xhr = xhr;
const self = this;
this.xhr.upload.addEventListener("progress", function(e) { // <--- this!
if (e.lengthComputable) {
const percentage = Math.round((e.loaded * 100) / e.total);
self.ctrl.update(percentage);
}
}, false);
xhr.upload.addEventListener("load", function(e){
self.ctrl.update(100);
const canvas = self.ctrl.ctx.canvas;
canvas.parentNode.removeChild(canvas);
}, false);
xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
reader.onload = function(evt) {
xhr.send(evt.target.result);
};
reader.readAsBinaryString(file);
}
I couldn't find a similar hook for the fetch API, but that surely must exist, right?
How do you keep the user updated with regard to upload progress if you want to use the fetch API to upload files?