zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [LeetCode] 137. Single Number II
    [LeetCode] 136. Single Number
    [LeetCode] 678. Valid Parenthesis String
    [LeetCode] 605. Can Place Flowers
    [LeetCode] 419. Battleships in a Board
    [LeetCode] 1002. Find Common Characters
    [LeetCode] 912. Sort an Array
    [LeetCode] 350. Intersection of Two Arrays II
    [LeetCode] 349. Intersection of Two Arrays
    [LeetCode] 820. Short Encoding of Words
  • 原文地址:https://www.cnblogs.com/coder-lzh/p/10435617.html
Copyright © 2011-2022 走看看