fetch下载进度条

fetch(url).then((response) => {
        if (response.status == 200) {
        	// 进度条相关
        	// 获取 Response 对象的 body 属性的读取器(reader)。body 属性是一个可读的流(ReadableStream),可以用来读取响应体的数据。
            const reader = response.body.getReader();
            const contentLength = +response.headers.get('Content-Length');
            let receivedLength = 0;
            let chunks = [];
            // 读取一个数据块。这个方法返回一个 Promise,当一个数据块被读取时,这个 Promise 就会解析为一个包含 done 和 value 属性的对象。done 属性表示是否已经读取完所有数据,value 属性是一个 Uint8Array,包含了读取到的数据块。
            return reader.read().then(function processChunk({ done, value }) {
                if (done) {
                    // 将 chunks 数组中的所有数据块复制到一个新的 Uint8Array 中,然后使用这个 Uint8Array 创建一个 Blob 对象
                    let data = new Uint8Array(receivedLength);
                    let position = 0;
                    for(let chunk of chunks) {
                        data.set(chunk, position);
                        position += chunk.length;
                    }
                    return new Blob([data]);
                }
                // 将读取到的数据块添加到 chunks 数组中。
                chunks.push(value);
                // 更新已接收的数据长度。
                receivedLength += value.length;
                console.log(`已下载:${receivedLength},总大小:${contentLength}`);
                // 递归调用 reader.read(),直到读取完所有数据。
                return reader.read().then(processChunk);
            });
        } else {
           console.log('下载失败')
        }
    })
    .then((blob) => {
        console.log('下载完成');
        //保存文件
    })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值