直接上代码:
/**
*
* @param fileUrl 文件下载URL
* @param fileName 下载文件名称
* @param onProgress 下载进度显示
*/
toDownload(fileUrl, fileName, onProgress) {
if (!fileName) {
fileName = decodeURIComponent(fileUrl.split('/').pop());
}
http({
url: fileUrl,//文件下载地址
method: 'get',//请求方式
responseType: 'blob',//服务端回复方式
withCredentials: false,//不携带cookie
onDownloadProgress: (progressEvent) => {
if (progressEvent.lengthComputable && typeof onProgress === 'function') {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
onProgress(percentCompleted);
}
}
}).then(({ data }) => {
let blob = data;
const elink = document.createElement('a')
if ('download' in elink) { // 非IE下载
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
//延迟释放,防止报错
setTimeout(() => {
URL.revokeObjectURL(elink.href);
}, 1000);
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
console.log(data);
}).catch(err => {
console.error('下载失败:', err);
});
}axios这样实例化就行
const http = axios.create({
timeout: 1000 * 60 * 3,
withCredentials: true,
})使用
const fileLink="https://www.yangguangdream.com/zb_users/upload/2025/06/wxacode_8e51cd37a5adda84.jpg";
const fileName="小程序码.jpg";
this.toDownload(fileLink, fileName, (percentCompleted) => {
console.log(`下载进度:${percentCompleted}%`);
});
微信扫码查看本文
发表评论