Large File Downloads with StreamSaver.js

Large File Downloads with StreamSaver.js

7月 26, 2024 · 1 分钟阅读时长 · 179 字 · -阅读 -评论

If you use the blob object for browser-side file downloads and then call the URL.createObjectURL(blob) method, the file will be downloaded directly. However, the downside is that it only supports small file downloads. How can we solve this without changing the backend? StreamSaver.js was created to address this issue.

Principle

StreamSaver.js uses ServiceWorker to intercept requests. If the result of the request is a stream, it can be continuously written to the local browser side. This breaks the limitation of JS single-thread, allowing large file downloads without blocking the thread.

Usage

import streamSaver from 'streamsaver';

streamSaver.mitm = 'https://example.com/custom_mitm.html';

const fileStream = streamSaver.createWriteStream('hello.mkv', { size: 10_000_000 });
const fileWriter = fileStream.getWriter();

fileWriter.write(new Uint8Array(chunk));

fileWriter.close();

Browser Compatibility

Since StreamSaver.js uses ServiceWorker, it is not supported in browsers that do not support ServiceWorker. For example, Firefox versions below 100 do not support WritableStream and require a polyfill to solve this issue.

https://unpkg.com/web-streams-polyfill@4.0.0/dist/polyfill.js

https://static.1991421.cn/2024/2024-07-26-223435.jpeg

At the end

The above is just one method for large file downloads. Additionally, the server can directly support stream downloads. Which solution to use depends on the specific scenario.

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源