js 实现blob下载文件

【js 实现blob下载文件】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 = https://www.it610.com/article/URL.createObjectURL(blob); a.download = fileName +'.pdf'; a.click(); URL.revokeObjectURL(a.href); a.remove(); }

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

    推荐阅读