前端代码如下:
handleDownloads(id, name) {
const href = this.$http.adornUrl(`/gen/gentable/statementDownload/${id}`)
this.$http({
url: href,
method: 'get',
params: this.$http.adornParams(),
responseType: 'blob'
}).then(({data}) => {
if (data ) {
let fileName = name;
if (fileName && fileName.indexOf('.') !== -1) {
fileName = fileName.slice(0, fileName.indexOf('.'))
}
const blob = new Blob([data], {
type: data.type
})
// 非IE 及edge下载
if ('download' in document.createElement('a') && navigator.userAgent.indexOf('Edge') <= -1) {
const elink = document.createElement('a')
if (fileName) {
elink.download = fileName
}
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
fileName ? navigator.msSaveOrOpenBlob(blob, fileName) :
navigator.msSaveOrOpenBlob(blob)
}
}
})
},
后端代码如下:
@RequestMapping(value = "/statementDownload/{id}")
public void statementDownload(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
GenStatementEntity statementEntity = genStatementService.getById(id);
String rpath = statementEntity.getLocation();
File file = new File(rpath);
FileInputStream fis;
fis = new FileInputStream(file);
long size = file.length();
byte[] data = new byte[(int) size];
fis.read(data, 0, (int) size);
fis.close();
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename="+ Encodes.urlEncode(file.getName()));
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}