js下载文件
普通的jQuery中的ajax请求后台,并不能处理Blob类型的数据,这里用的原生的XMLHttpRequest请求后台
转自:https://blog.csdn.net/lf1934305268/article/details/123401275
var xhr = new XMLHttpRequest();
xhr.open("get",url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
$.unblockUI();
var blob = this.response;
if(blob.type == "text/html"){
return false
}
var fileName = "aaaa.xlsx";
if(window.navigator.msSaveOrOpenBlob){ // IE浏览器下
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}else{
}
}另:IE浏览器已不再使用,可以删除对IE浏览器的判断
我的代码:
var xhr = new XMLHttpRequest();
xhr.timeout = 600000; //设置超时毫秒数(0为永不超时)
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function(){
if(this.status != 200){
return;
}
var blob = this.response;
if(blob.type == "text/html"){
console.log('error');
return false;
}
var allow_type=['video/quicktime','video/mp4'];
if(allow_type.indexOf(blob.type)==-1){
console.log('content-type not allowed');
return false;
}
console.log(filename+' 下载完成,大小'+blob.size+'字节');
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(a.href);
}
xhr.onerror = function(){
console.log('error');
console.log(this.status);
console.log(this);
}
xhr.ontimeout = function(){
console.log('timeout');
console.log(this.status);
console.log(this);
}
xhr.send();
