vue cli + axios + springboot 实现文件下载
小明 Lv6

环境准备

install axios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cnpm install axios --save

<script>
import axios from 'axios';
export default {
data() {
return {
...
}
},
methods:{
...
}
}
</script>

前端代码

执行的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
downLoadMix() {  
let params = {};
let url = this.$store.state.urlPrefix+"/company/download";
let title = null;
axios({
method: 'post',
url,
headers: {
'Content-Type': 'application/json'
},
data: params,
responseType: 'arraybuffer'
}).then(res => {
let headers = res.headers; //后端需要配置Access-Control-Expose-Headers,否则浏览器只能访问到默认的响应头,具体如下
let blob = new Blob([res.data], {
type: headers['content-type']
});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
if (!title) {
const fileName = headers['content-disposition'];
title = fileName.includes('filename=') ? fileName.split('=')[1] : '下载的表单文件';
}
link.download = title;
link.click();
});
}

后端代码(解决axios获取Http响应头)

浏览器默认只能访问以下响应头

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

因此如果想让浏览器能访问到其他响应头内容的话,比如Content-disposition,需要在服务器上设置 Access-Control-Expose-Headers

1
response.setHeader("Access-Control-Expose-Headers","Content-disposition");

或者完全放开

1
response.setHeader("Access-Control-Expose-Headers","*");

即可允许浏览器访问任意一个响应头,当然除次之外还要设置下载文件相关的响应头

1
2
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=createList.xls");//默认Excel名称

后端i/o流照常处理,例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RequestMapping(value = "/download", method = {RequestMethod.POST}, produces = {"application/json;charset=UTF-8"})
public void download(@RequestBody RequestFacade request, HttpServletResponse response) {
try{
//创建工作簿
XSSFWorkbook wb = new XSSFWorkbook();
//创建一个sheet
XSSFSheet sheet = wb.createSheet();

// 创建单元格样式
XSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.WHITE.index);

......

response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=createList.xls");//默认Excel名称
response.setHeader("Access-Control-Expose-Headers","*");
response.flushBuffer();
wb.write(response.getOutputStream());
}catch (Exception e) {
e.printStackTrace();
}
}
 评论