明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

js下载文件 监听下载完成事件

Posted on 2022-05-24 18:26  且行且思  阅读(2720)  评论(0编辑  收藏  举报

//下载时加载的操作 load = function() { down_windows = layer.msg("数据正在下载中", { icon: 16, shade: 0.3, time: -1 }); } //下载完成后触发,用来关闭提示框 disload = function() { layer.close(down_windows) } // 下载使用的方法 getDownload = function(url) { var xhr = new XMLHttpRequest(); if(typeof(xhr) !="undefined") { // 现在使用的方法 可在下载完成的时候关闭load弹窗 load(); 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"); a.download = decodeURIComponent(headerName).substring(20); a.href = URL.createObjectURL(blob); $("body").append(a); // 修复firefox中无法触发click a.click(); URL.revokeObjectURL(a.href); $(a).remove(); } else { navigator.msSaveBlob(blob, decodeURIComponent(headerName).substring(20)); } } disload(); }; xhr.send(); } else { window.location.href = url; } };

 

<script src="xxx/layui/layui.js"></script>
<script src="xxx/jquery.min.js"></script>