ResponseEntity下载文件

前端依赖

FileSaver.js

前端angular

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
28
29
30
31
32
33
34
35
36
import FileSaver from '../xxx/FileSaver.js';

const params = {
};
return this.$http({
method: 'GET',
url: '/download.json',
// responseType必须值,否则文件下载后乱码
responseType: 'arraybuffer',
params: params
}).then(function (response) {
let body = response.data;
let contentDisposition = response.headers('Content-Disposition');
// 获取文件名
let fileName;
for (let key of contentDisposition.split(';')){
let name = key.split('=')[0].trim();
if (name === 'filename'){
fileName = key.split('=')[1].trim();
// 解决中文乱码
fileName = decodeURIComponent(escape(fileName));
// 去除首尾多余双引号
fileName = fileName.replace(/"/g, '');
}
}
if (body) {
let file = new Blob([body], {
type: "application/octet-stream"
});
FileSaver.saveAs(file, fileName);
} else {
// 下载失败
}
}).catch(error => {
this.$log.log(error);
});

后端

1
2
3
4
5
6
7
8
9
10
@GetMapping("/download.json")
public ResponseEntity<byte[]> download() {
byte[] bytes;
HttpHeaders headers = new HttpHeaders();
String filename = new String(new String("file.xlsx").getBytes("utf-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", filename);
headers.setContentLength(bytes.length);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}
>