后端代码:
可以把请求设置为post,我这里是Get
@RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletRequest request, HttpServletResponse res) throws Exception {
File excelFile = new File("/Users/i501695/GitHUbProject/EN_ProductIntergration/databaseclient/src/main/resources/Files/ProductTemplateCopy.xlsx");
res.setCharacterEncoding("UTF-8");
String realFileName = excelFile.getName();
res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
res.setContentType("application/octet-stream;charset=UTF-8");
//加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
res.addHeader("Content-Length", String.valueOf(excelFile.length()));
try {
res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = res.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(excelFile));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
前端伪代码结合Axios(核心代码一样,只是结合了Axios)
Axios({ // 用axios发送post请求
method: 'post',
url: 'http://127.0.0.1:8762/dataService/download', // 请求地址
data: formData, // 参数
responseType: 'blob' // 表明返回服务器返回的数据类型
})
.then((res) => { // 处理返回的文件流
let blob = new Blob([res.data], {type: res.data.type})
const fileName = 'ProductTemplateCopy.xlsx';
let downloadElement = document.createElement('a')
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = fileName; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放blob
message.success('upload successfully.');
})
.catch(function (error) {
console.log(error);
});