后台使用SpringMVC 的 ResponseEntity<byte[]> 参数返回类型,前台使用AngularJs请求。代码如下
后台代码:
@RequestMapping("/down")
@ResponseBody
public ResponseEntity<byte[]> expoertExcel(..) throws IOException{
...
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpheaders, HttpStatus.CREATED);
}
前台angularJs接受方式有两种,一种是可以预先设置下载文件的名称,一种是不设置的。但是两种方法都是使用的存储二进制对象blob来实现下载的
第一种模拟连接触发(可以设置下载的文件名称):
$http({
method : 'POST',
url : url,
data : data,
headers : {
'Content-type' : 'application/json;charset=UTF-8'
},
responseType: 'arraybuffer',
transformRequest : function(obj) {
return JSON.stringify(obj);
}
}).success(function (data) {
//type对应着所需要下载的文件类型
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="Excel.xls";
a.set`Attribute('download', filename);
a.click();
URL.revokeObjectURL(objectUrl);
}).error(function (data) {
....
});
第二种方式:
$http({...}).success(function (data) {
var blob = new Blob([data], {type: "application/vnd.ms-excel"});
var fileUrl = URL.createObjectURL(blob);
window.open(fileUrl);
})