前端依赖
FileSaver.js
前端
import FileSaver from '../xxx/FileSaver.js';
const params = {
};
return this.$http({
method: 'GET',
url: '/download.json',
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);
});
后端
@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);
}