【代码】axios Blob下载文件与进度监听

2025-07-04 14:19:06  阅读 23 次 评论 0 条

直接上代码:

 /**
         * 
         * @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}%`);
            });



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2258
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!
NEXT:已经是最新一篇了

发表评论


表情

还没有留言,还不快点抢沙发?