if (window.navigator.msSaveOrOpenBlob) {
// 兼容IE10
navigator.msSaveBlob(blob, downName)
} else {
// chrome/firefox
let aTag = document.createElement('a')
aTag.download = downName
aTag.href = URL.createObjectURL(blob)
aTag.click()
URL.revokeObjectURL(aTag.href)
}
- ie8没有
navigator.msSaveBlob
,也没有Blob
对象,创建a标签下载也会报错error: 拒绝访问
,简直离谱,即使根据我上一篇拒绝访问的方法(IE8发送ajax方法解决)去弄,也是没有任何反应
网上的方法
- 使用
window.open
或者iframe
,用这个方法,在我电脑上点击,IE直接黑屏无响应了。。
var DownLoad = function (url, name) {
if (!!window.ActiveXObject || "ActiveXObject" in window) {
//ie
var oPow = window.open(url, "", "width = 1, height = 1, top = 5000, left = 5000 ");
var isOpen = true; //判断window.open是否被禁用
try {
if (oPow == null) {
isOpen = false
}
} catch (err) {
isOpen = false
}
if (isOpen) {
//没禁用window.open采用window.open下载
while (oPow.document.readyState !== "complete") {
if (oPow.document.readyState === "complete") break;
}
oPow.document.execCommand("SaveAs", true, name);
oPow.close();
} else {
//禁用了window.open采用iframe下载
var oIrame = document.createElement('iframe');
oIrame.style.width = "0px";
oIrame.style.height = "0px";
oIrame.style.opacity = 1;
document.body.appendChild(oIrame)
oIrame.src = url;
var IfDoc = oIrame.contentDocument || oIrame.document;
oIrame.onreadystatechange = function () { // IE下的节点都有onreadystatechange这个事件
if (oIrame.readyState == "complete") {
// oIrame.execCommand("SaveAs", true, name)
document.body.removeChild(oIrame)
}
};
}
} else {
if (typeof url == 'object' && url instanceof Blob) {
url = URL.createObjectURL(url); // 创建blob地址
}
var aLink = document.createElement('a');
aLink.href = url;
aLink.download = name || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
var event;
if (window.MouseEvent) {
event = new MouseEvent('click');
} else {
if (document.createEvent) {
event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
}
aLink.dispatchEvent(event);
}
}
- 还有一种方法是我想的,也不行,也是请求的后台数据流,但是请求报错500,后台说请求到后台就断开握手了,不知道是IE的问题还是啥。。
$.ajax({
url,
method: "get",
dataType: "json",
responseType: "blob"
});
解决方法
- 使用form表单提交,中间的input是传参,会放在FormData里面
$(
"<form action='"+src + "' method='get'>" +
"<input type='text' name='city' value='" + CITY + "'/>" +
"</form>"
).appendTo("body").submit().remove();