通常下载一个文件用
window.location.href = "接口内容"
就能实现下载一个文件的需求。
但是如果遇到一些特殊的需求,比如说需要在请求头重加一些属性和值,这样window.location.href就不能满足了。但是可以用angularJS自带的$http来请求。
$http({
url: '你的接口内容',
method: "GET",//接口方法
params: {
//接口参数
},
headers: {
'Content-type': 'application/json'
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
var blob = new Blob([data], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display:none');
a.setAttribute('href', objectUrl);
var filename="充值记录.xls";
a.setAttribute('download', filename);
a.click();
URL.revokeObjectURL(objectUrl);
}).error(function (data, status, headers, config) {
});
以上代码就可以下载excel.
接下来画一下重点:
1.responseType: 'arraybuffer',这个属性一定要添加上,不然返回数据类型会出错。
2.var blob = new Blob([data], {type: "application/vnd.ms-excel"});
导出文件的格式是在这里定义。
其实返回文件的格式有很多种定义:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
application/vnd.ms-excel
关键是要选择哪一种是自己需要的
以上。
后续:
angularjs 1.6之后$http没有success,error方法,所以你框架如果是1.6以上的话,按照以上写会报如下错:
$http(...).success is not a function。。。。。
改成如下格式:
$http({
url: '',
method: 'get'
}).then(function (data){
.....
})