注意 :通常下载文件是用get请求
window.location.href=url;
但是 我们需要下载完成监听,所以必须要异步执行、用常规的ajax是不可以的。我们要用blob对象来实现
1.原生的如何实现
function loadDown(query) { ???????var url = "${ctx}/bill/billExport"+query; ???????var xhr = new XMLHttpRequest(); ???????xhr.open(‘GET‘, url, true); // 也可以使用POST方式,根据接口 ???????xhr.responseType = "blob"; ???????xhr.onload = function () { ???????????if (this.status === 200) { ???????????????$(‘#loadingModal‘).modal(‘hide‘); ???????????????var content = this.response; ???????????????var aTag = document.createElement(‘a‘); ???????????????var blob = new Blob([content]); ???????????????var headerName = xhr.getResponseHeader("Content-disposition"); ???????????????var fileName = decodeURIComponent(headerName).substring(20); ???????????????aTag.download = fileName; ???????????????aTag.href = URL.createObjectURL(blob); ???????????????aTag.click(); ???????????????URL.revokeObjectURL(blob); ???????????} ???????}; ???????xhr.send() ???}
2 ajax如何实现
$.ajax({ ???????????url:options.url, ???????????// dataType:"text", ???????????// type:"get", ???????????success:function(result){ ???????????????var content = this.response; ???????????????var aTag = document.createElement(‘a‘); ???????????????var blob = new Blob([content]); ???????????????var headerName = xhr.getResponseHeader("Content-disposition"); ???????????????var fileName = decodeURIComponent(headerName).substring(20); ???????????????aTag.download = fileName; ???????????????aTag.href = URL.createObjectURL(blob); ???????????????aTag.click(); ???????????????URL.revokeObjectURL(blob); ???????????} ???????})
后台:
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
参考博客:https://blog.csdn.net/Concsdn/article/details/79961295
https://blog.csdn.net/weixin_38661747/article/details/80754258
js异步下载文件请求
原文地址:https://www.cnblogs.com/coder-lzh/p/10435617.html