实现JS监听文件下载完成的功能

3,416 阅读1分钟

一般来说,我们的js文件下载会使用window.location.href定位到后端的接口,后端生成文件返回,然后浏览器自动下载。这种方法最简单,但是无法获取下载成功的通知,在大文件生成和下载的时候,时间过长,用户可能会重复进行下载的点击,对服务器造成负担。同时解决解决不同浏览器的下载触发 + a标签base64url过长无法下载的问题。

load = function() {
	var index = layer.load(1, {
		shade: [0.25, '#333'] //0.1透明度的白色背景
	});
	//此处我用的事layui的loading事件可以填写你的下载时加载的提示
}
disload = function() {
	layer.close(index);
	//下载完成后触发,用来关闭提示框
}
getDownload = function(url) {
	load();
	var xhr = new XMLHttpRequest();
	xhr.open('GET', url, true); // 也可用POST方式
	xhr.responseType = "blob";
	xhr.onload = function() {
		if (this.status === 200) {
			var blob = this.response;
			if (navigator.msSaveBlob == null) {
				var a = document.createElement('a');
				var headerName = xhr.getResponseHeader("Content-disposition");
				var fileName = decodeURIComponent(headerName).substring(20);
				a.download = fileName;
				a.href = URL.createObjectURL(blob);
				$("body").append(a);
				a.click();
				URL.revokeObjectURL(a.href);
				$(a).remove();
			} else {
				navigator.msSaveBlob(blob, fileName);
			}
		}
		disload();
	};
	xhr.send()
};