2

I need the feature to be able to upload image files in background without making the user wait till all the files are uploaded. I want to use a web worker to do so but don't know how will the formdata of the images to be uploaded will be sent to the worker.js.

While the upload takes place the user should also be able to move around the we page and simultaneously the upload is also taking place. How to do this? I understand the basic of how the worker work and how to communicate with worker but I don't know how to send data to the worker for some work to be done in background.

Alex Sergeenko
  • 642
  • 5
  • 22
RKD1996
  • 61
  • 1
  • 7
  • is there a reason why you specifically wanted to use Web Worker when it is completely doable with AJAX? – Julian Paolo Dayag Aug 02 '18 at 05:46
  • yes because large file will be uploaded and the user will have to wait a lot if it takes more time to upload – RKD1996 Aug 02 '18 at 05:50
  • AJAX is asynchronous/non-blocking so the user don't have to wait. – Julian Paolo Dayag Aug 02 '18 at 05:52
  • @IVOGELOV That’s completely incorrect: there is no requirement that `fetch` and/or `XMLHttpRequest` requests be sequential nor serial: on the contrary: you _can_ fire-off concurrent requests, even multiple requests to the same host ([the per-host connection limit is now 6, not 2 like it used to be](https://stackoverflow.com/questions/985431/max-parallel-http-connections-in-a-browser)) and you can await some or all using `Promise.all` and `Promise.race`. Nor does any pending or incomplete request block the user’s page navigation. – Dai Aug 29 '21 at 06:10

1 Answers1

3

The trick is to use readAsArrayBuffer to transfer the file contents to a web worker - and then use a normal XHR or Fetch request:

 const fr = new FileReader();
 fr.readAsArrayBuffer(file);
 fr.onloadend = heap => this.worker.postMessage({
     command: 'TransferProfile',
     data: {
         heap
     }
 }, [heap]); //Passing [heap] as a 2nd parameter flags it as Transferable

If your files are really large (so reading them in RAM is not feasible) - you may find the Resumable.js more suitable for your case.

IVO GELOV
  • 13,496
  • 1
  • 17
  • 26