JavaScript 使用 fetch 获取文件下载进度

130 阅读1分钟

文件上传和下载是常见的功能。用户往往希望能够实时了解下载进度,以便于管理和控制下载过程,下面将介绍如何使用 fetch 实现文件下载进度的跟踪。

代码示例如下:

async function fetchProgress() {
    const response = await fetch('xxx');
    const responseOriginal = response.clone();

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');

    const contentLength = +response.headers.get('Content-Length');
    let currentLength = 0;

    while (true) {
        const { done, value } = await reader.read();
        if (done) {
            break;
        }

        currentLength += value.length;
        updateProgress(currentLength, contentLength);
    }

    const contentType = response.headers.get('Content-Type');
    const blob = await responseOriginal.blob();

    downloadFile(blob, contentType);
}

const updateProgress = (received, total) => {
    const percent = Math.round((received / total) * 100);
    return `下载进度: ${percent}%`;
};

const downloadFile = (data, type) => {
    const blob = new Blob([data], { type });
    const href = window.URL.createObjectURL(blob);

    const el = document.createElement('a');
    el.href = href;
    el.download = `${Date.now()}.png`;

    document.body.appendChild(el);
    el.click();
    document.body.removeChild(el);
    window.URL.revokeObjectURL(href);
};

fetchProgress();