【问题标题】:How to check file download status using javascript/JQuery at client side如何在客户端使用 javascript/JQuery 检查文件下载状态
【发布时间】:2020-12-15 23:20:08
【问题描述】:
用户点击网页上的按钮下载文件,我想跟踪文件正在下载到用户机器还是没有使用像javascript/JQuery这样的客户端代码。
单击按钮时,调用 ASP.NET .ASHX Web 处理程序代码,返回要下载的文件。
当用户点击网页上的下载按钮时,我们还可以使用 javascript/JQuery 检查用户在下载文件时是否遇到问题(安全、防火墙等)。
【问题讨论】:
标签:
javascript
jquery
file
download
status
【解决方案1】:
这可以通过附加到 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();