Stream File Download in Safari and Firefox

Viewed 1002

Currently, as a requirement, if a user wishes to download a large zip file, the download is a streamed.

This is done by fetching an endpoint, then using Streamsaver.js to stream the download to their browser as shown below.

function download(id, fileName) {
  const endpoint = `.../extract/downloads/zip_download/?id=${id}`;
  return fetch(endpoint, requestOptions.get()).then(res => {
    const downloadSize = res.headers.get("content-length");
    const fileStream = createWriteStream(fileName, { size: downloadSize });
    const writer = fileStream.getWriter();
    if (res.body.pipeTo) {
      writer.releaseLock();
      return res.body.pipeTo(fileStream);
    }

    const reader = res.body.getReader();
    const pump = () =>
      reader
        .read()
        .then(({ value, done }) =>
          done ? writer.close() : writer.write(value).then(pump)
        );

    return pump();
  });
}

This works fine in Chrome, however I'm running into issues with Firefox and Safari. The issue I get is:

TypeError: undefined is not a constructor (evaluating 'new streamSaver.WritableStream')

What other methods are there of approaching this? Surely there must be a universal way to stream a download of a large that I'm missing?

1 Answers

I ran into the same issue and included the web-streams-polyfill package in my project to fix it. Currently, some non-chromium browsers appear to not support WritableStream.

For myself, I simply included this script tag in my index.html

<script src="https://unpkg.com/web-streams-polyfill/dist/polyfill.min.js"></script>

Related