js異步下載文件請求


注意 :通常下載文件是用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM