如何在客户端使用javascript / jquery检查文件下载状态

问题描述

用户单击网页上的按钮下载文件,我想跟踪文件正在下载到用户计算机上还是不使用诸如javascript / JQuery之类的客户端代码。

单击按钮时,将调用ASP.NET .ASHX Web处理程序代码,该代码返回要下载的文件。

当用户单击网页上的下载按钮时,我们还可以使用javascript / JQuery检查用户在下载文件时是否遇到问题(安全性,防火墙等)。

解决方法

这可以通过附加到AJAX请求的“进度”事件来完成。

let xhr = new XMLHttpRequest();
xhr.addEventListener("progress",event=>{
  console.log(`${event.loaded} out of ${event.total}`);
});

然后可以通过创建错误的链接来链接到文件数据并保存在内存中,从而通过AJAX处理下载:

xhr.onreadystatechange(function(){
  if(this.readyState==4 && this.status==200){
    //Download content via imaginary link with data saved in memory
    var a = document.createElement('a');
    var url = window.URL.createObjectURL(this.response);
    a.href = url;
    a.download = 'myfile.pdf';
    document.body.append(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  }else if(this.status==404){
    console.error("page not found");
  }
});
xhr.open("GET","myfile.pdf",true);
xhr.responseType = "blob";
xhr.send();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...