// 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;
}
},
JavaScript实现分块下载文件
最新推荐文章于 2025-09-02 11:23:20 发布
4044

被折叠的 条评论
为什么被折叠?



