fileUpload.ts
export function downloadFileWithProgress(url, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob"; // 返回二进制数据
// 监听下载进度
xhr.onprogress = (event) => {
if (event.lengthComputable && typeof onProgress === "function") {
const percent = (event.loaded / event.total) * 100;
onProgress(percent.toFixed(2)); // 更新进度回调
}
};
// 监听成功完成下载
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response); // 返回 Blob 对象
} else {
reject(new Error(`下载失败,状态码:${xhr.status}`));
}
};
// 监听下载错误
xhr.onerror = () => {
reject(new Error("下载过程中发生错误"));
};
xhr.send();
});
}
xxx.vue 中调用
import { downloadFileWithProgress } from '@/utils/fileUpload';
downloadFileWithProgress(downloadUrl, (progress) => {
console.log(`下载进度:${progress}%`);
})
.then((blob) => {
downloadLoading.value = false
// 创建下载链接
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${detail.value.content.name}.${detail.value.content.ext}`; // 指定下载文件名
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); // 释放 URL
console.log("下载完成!");
})
.catch((error) => {
console.error("下载失败:", error.message);
});
})