JavaScript实现分块下载文件

// url: 下载地址;fileName: 文件名称;that: this; num: 当前进度; chunkSize: 分块大小默认3M
async getProgress(url, fileName, that, num = 0, chunkSize = 1024 * 1024 * 3) {
        try {
            // 1. 获取文件总大小
            const headResponse = await fetch(url, { method: 'HEAD' });
            const totalSize = parseInt(headResponse.headers.get('content-length'));
            
            let receivedBytes = 0;
            const chunks = [];
            
            // 2. 分块下载
            while (receivedBytes < totalSize) {
                const end = Math.min(receivedBytes + chunkSize - 1, totalSize - 1);
                const chunkResponse = await fetch(url, {
                    headers: { Range: `bytes=${receivedBytes}-${end}` }
                });
                
                if (!chunkResponse.ok) throw new Error('Chunk download failed');
                
                const chunk = await chunkResponse.blob();
                chunks.push(chunk);
                receivedBytes += chunk.size;
                
                // 3. 更新进度
                const percent = Math.min(99, (receivedBytes / totalSize) * 100); // 最大99%
                if (num === 0) {
                    that.percentage = percent;
                } else if (percent > num) {
                    that.percentage = percent;
                }
            }
            
            // 4. 合并并下载
            const fullBlob = new Blob(chunks);
            const downloadUrl = window.URL.createObjectURL(fullBlob);
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = fileName.includes('.') ? fileName : `${fileName}_${new Date().getTime()}.xlsx`;
            document.body.appendChild(a);
            a.click();
            
            // 5. 清理
            setTimeout(() => {
                window.URL.revokeObjectURL(downloadUrl);
                document.body.removeChild(a);
                that.percentage = 100;
                that.progressShow = false;
            }, 1000);
            
            // 6. 删除临时文件
            const index = url.indexOf('uploads');
            if (index !== -1) {
                const str = url.slice(index);
                that.$http.get('del_export_excel_files/?file=' + str);
            }
        } catch (error) {
            console.error('Download failed:', error);
            that.$message.error('下载失败');
            that.progressShow = false;
        }
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值