You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

axios请求中onDownloadProgress事件无法触发问题求助

解决axios onDownloadProgress不触发的问题

核心问题:配置参数结构错误

你的代码里把onDownloadProgress放到了axios的第二个独立参数中,但axios发起请求时,所有配置项都应该放在同一个配置对象里,第二个参数在这里是无效的,这直接导致回调无法被触发。

修正后的代码

axios({
    url: "/rest/downloadInfo",
    method: 'GET',
    responseType: 'blob', 
    onDownloadProgress: (progressEvent) => {
        if (progressEvent.lengthComputable) {
            let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log(percentCompleted);
        } else {
            console.log("无法计算下载进度");
        }
    }
}).then((response) => {
    const href = URL.createObjectURL(response.data);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'downloadFile.zip');
    
    document.body.appendChild(link);
    link.click();

    document.body.removeChild(link);
    URL.revokeObjectURL(href);
});

额外排查点

  • 检查Content-Length响应头:服务器必须返回Content-Length头,且值为文件的实际字节大小,否则progressEvent.lengthComputable会是false,无法计算准确进度,需要后端配合设置该响应头。
  • 禁用gzip压缩(如果启用):如果服务器对下载接口开启了gzip压缩,Content-Length会是压缩后的文件大小,导致进度计算不准确,甚至出现进度值超过100%的情况,可让后端单独为该下载接口禁用压缩。
  • 更新axios版本:旧版本axios可能存在onDownloadProgress的兼容性问题,确保使用最新稳定版。

内容的提问来源于stack exchange,提问作者Marcus Allen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:05:01