关于javascript:js-实现blob下载文件

9次阅读

共计 756 个字符,预计需要花费 2 分钟才能阅读完成。

1. 首先创立一个 HTTP 申请

let xhr = new XMLHttpRequest();
    xhr.open('get', url, true);  //url 为地址链接
    xhr.setRequestHeader('Content-Type', `application/${type}`);
    xhr.responseType = "blob";
    xhr.onload = function () {if (this.status == 200) {
        // 承受二进制文件流
        var res = this.response;
        downloadExportFile(res, fileName, type)
      }
    }
    xhr.send();}

@param res:文件链接
@param fileName:文件名;
@param type:文件类型;

2. 创立 blob

function downloadExportFile (res,fileName,type) {const blob = new Blob([res],{type:'application/${type}'});
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = fileName + '.pdf';
    a.click();
    URL.revokeObjectURL(a.href);
    a.remove();}

这样就实现 blob 下载文件性能了。
公布到测试环境后发现点击后会报错:Mixed Content: The page at..HTTPS 中蕴含 http 的不平安问题,解决方案:
在 html 页面中增加

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
正文完
 0