$.ajaxDownload=function(opt){
var defaults = {
url:'',
type:'GET',
parameters:null,
onloadstart:null,
ontimeout:null,
onerror:null,
onloadend:null
}
var settings = $.extend(true,{}, defaults, opt);
var xhr = new XMLHttpRequest();
xhr.open(settings.type, settings.url, true);
xhr.responseType = "blob"; // 返回类型blob
if(typeof FormData == "undefined") {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if(Object.prototype.toString.call(settings.onloadstart)==="[object Function]"){
xhr.onloadstart=settings.onloadstart;
}
if(Object.prototype.toString.call(settings.onerror)==="[object Function]"){
xhr.onerror=settings.onerror;
}
if(Object.prototype.toString.call(settings.onloadend)==="[object Function]"){
xhr.onloadend=settings.onloadend;
}
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
// 返回200
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
var a = document.createElement('a');
a.download = settings.parameters.fileName;
a.href = e.target.result;
$("body").append(a); // 修复firefox中无法触发click
a.click();
$(a).remove();
}
}
};
xhr.send(postDataFormat(settings.parameters))// 发送ajax请求
function postDataFormat(obj){
if(typeof obj != "object" ) {
alert("输入的参数必须是对象");
return;
}
// 支持有FormData的浏览器(Firefox 4+ , Safari 5+, Chrome和Android 3+版的Webkit)
if(typeof FormData == "function") {
var data = new FormData();
for(var attr in obj) {
data.append(attr,obj[attr]);
}
return data;
}else {
// 不支持FormData的浏览器的处理
var arr = new Array();
var i = 0;
for(var attr in obj) {
arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);
i++;
}
return arr.join("&");
}
}
}
console