前端采用异步方式请求
axios({
method: 'POST',
url: this.downTemplateUrl,
params: {
type: 1
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
responseType: 'blob'
}).then(res => {
let blob = new Blob([res.data], {type: "application/vnd.ms-excel;charset=UTF-8"});
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)
let downFile = document.createElement('a')
downFile.style.display = 'none'
downFile.href = objectUrl
downFile.download = fileName // 下载后文件名
document.body.appendChild(downFile)
downFile.click()
document.body.removeChild(downFile) // 下载完成移除元素
// window.location.href = objectUrl
window.URL.revokeObjectURL(objectUrl) // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
}
}).catch(err=>{
console.log(err)
})
},
后端返回文件流:
public void downloadFile(HttpServletResponse response, String result) {
OutputStream os = null;
try {
response.setCharacterEncoding("UTF-8");
String path = SecurityTools.decrypt(result);
//response.setContentType("application/octet-stream");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
String fileName = path.substring(path.lastIndexOf("/") + 1);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
os = response.getOutputStream();
File file = new File(path);
final int length = 1024 * 1024;
ByteBuffer bytes = ByteBuffer.allocate(length);
SeekableByteChannel seekByte = Files.newByteChannel(file.toPath());
int read = -1;
while ((read = seekByte.read(bytes)) >= 1) {
os.write(bytes.array(), 0, read);
os.flush();
bytes.clear();
}
} catch (Exception e) {
log.error("下载失败," + e.getCause().getMessage());
} finally {
try {
if (os != null) {
os.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}