使用angularjs实现文件下载,一开始使用的方法如下:
function Service($resource) {
'downloadOrderFile': {
url: 'fileDownload/testFile',
method: 'POST',
responseType:'arraybuffer',
transformResponse: function(data, headers){
var response = {};
response.data = data;
response.headers = headers();
return response;
}
}
});
function downloadOrderFile() {
Service.downloadOrderFile({}, function(response) {
var fileName = response.headers['content-disposition'];
fileName = fileName.substring(fileName.indexOf("filename=") + 9);
fileName = decodeURI(fileName);
var url = URL.createObjectURL(new Blob([response.data]));
var a = document.createElement('a');
a.href = url;
a.download = fileName;
a.target = '_blank';
a.click();
},function(response) {
console.log(response);
});
}
结果测试出现的情况是:在Google浏览器中测试问题,而在firefox中实现却没有反应,F12查看请求情况,发现请求和返回都没有问题。于是猜测是前端代码的兼容性不行。最后的解决方案是:
function Service($resource) {
'downloadOrderFile': {
url: 'fileDownload/testFile',
method: 'POST',
responseType:'blob', //此处改为blob
transformResponse: function(data, headers){
var response = {};
response.data = data;
response.headers = headers();
return response;
}
}
});
function downloadOrderFile() {
Service.downloadOrderFile({}, function(response) {
var fileName = response.headers['content-disposition'];
fileName = fileName.substring(fileName.indexOf("filename=") + 9);
fileName = decodeURI(fileName);
var url = URL.createObjectURL(new Blob([response.data]));
var a = document.createElement('a');
document.body.appendChild(a); //此处增加了将创建的添加到body当中
a.href = url;
a.download = fileName;
a.target = '_blank';
a.click();
a.remove(); //将a标签移除
},function(response) {
console.log(response);
});
}
测试成功!
附:
后台实现
@RestController
@RequestMapping("/fileDownload")
public class FileDownLoadController {
@RequestMapping(value = "/testFile",method = RequestMethod.POST)
public void accountFile() throws URISyntaxException {
File file = new File("D:/123.xlsx");
if(file != null) {
response.reset();
FileInputStream fs = null;
OutputStream os = null;
try {
response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(file.getName(), "utf-8"));
response.setContentType("application/vnd.ms-excel;charset=GBK");
fs = new FileInputStream(file.getPath());
os = new BufferedOutputStream(response.getOutputStream());
int len = 0;
byte[] b = new byte[1024];
while ((len = fs.read(b)) > 0) {
os.write(b, 0, len);
}
fs.close();
os.flush();
os.close();
}catch(Exception ex) {
ex.printStackTrace();
}finally {
try {
if(fs != null) {
fs.close();
}
if(os != null) {
os.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}