整理几个页面下载文件的踩坑指南

203 阅读1分钟

window.open(‘下载地址’)//下载的时候会拉起新的页面

window.location.href=下载地址

以上两个也是坑,有些浏览器不触发  心累

iframe下载   可能会有跨域兼容性问题  反正我还没有发现

this.downloadFiles(下载地址)

downloadFiles(url) {

try{

var elemIF = document.createElement("iframe");

elemIF.src = url;

elemIF.style.display = "none";

document.body.appendChild(elemIF);

}catch(e){

}

}

//用from的形式   微信内打开页面链接是拉不起 下载的    

fromDownLoad(actionUrl){

let url = actionUrl;

const formhtml = `

`

const divDom = document.createElement("div");

divDom.innerHTML = formhtml;

document.body.appendChild(divDom);

document.getElementById("download").submit();

setTimeout(()=>{

document.body.removeChild(divDom)

})

}

//ajax 方式下载文件

load(){
  //下载前
}disload(){
//下载完成后
}
getDownload = function(url) {
	load();
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);    // 也可用POST方式
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = this.response;
            if (navigator.msSaveBlob == null) {
                var a = document.createElement('a');
                var headerName = xhr.getResponseHeader("Content-disposition");
                var fileName = decodeURIComponent(headerName).substring(20);
                a.download = fileName;
                a.href = URL.createObjectURL(blob);
                $("body").append(a);    // 修复firefox中无法触发click
                a.click();
                URL.revokeObjectURL(a.href);
                $(a).remove();
            } else {
                navigator.msSaveBlob(blob, fileName);
            }
        }
        disload();
    };
    xhr.send()
};