0

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 overloaded send() method for File or Blob 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 XMLHttpRequests 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);
}

https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications#example_uploading_a_user-selected_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?

connexo
  • 53,704
  • 14
  • 91
  • 128
  • 2
    (That dupe is an older question, but the answer https://stackoverflow.com/a/69400632/1427878 is from October 1st this year.) – CBroe Dec 14 '21 at 08:51
  • Thanks alot for the quick response. That is really a disappointer, given the fact how long we've had the fetch API. – connexo Dec 14 '21 at 08:58

0 Answers0