java后端
看一下文件放的位置
public void downloadSFDTemplateExcel(HttpServletResponse response) {
try {
InputStream inputStream = this.getClass().getResourceAsStream("/template/SFDTemplate.xlsx");
//强制下载不打开
response.setContentType("application/force-download");
OutputStream out = response.getOutputStream();
//使用URLEncoder来防止文件名乱码或者读取错误
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("SFDTemplate.xlsx", "UTF-8"));
int b = 0;
byte[] buffer = new byte[1000000];
while (b != -1) {
b = inputStream.read(buffer);
if (b != -1) out.write(buffer, 0, b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
- postman调用的展示
vue前端
前端api方法
import request from '@/utils/request'
const base_url = ''
const eds = '/thirdAdmin/sfd/api'
// 下载模板
export function downloadSFDTemplateExcel() {
return request({
url: base_url + eds + '/downloadSFDTemplateExcel',
responseType: 'blob',
method: 'get'
})
}
vue方法代码
//下载方法
downloadSFDTemplate(){
downloadSFDTemplateExcel().then((res)=>{
console.log(res)
const aLink = document.createElement('a');
//Blob中的type有很多,这里是下载excel中的xlsx
const blob = new Blob([res],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
aLink.href = URL.createObjectURL(blob);
aLink.setAttribute('download', "SFDTemplate.xlsx"); // 下载文件名称
document.body.appendChild(aLink);
aLink.click();
URL.revokeObjectURL(aLink.href); // 释放URL对象
document.body.removeChild(aLink);
})
},
补充:
1.Blob中类型有很多,本文只是下载excel,其他文件填写的
2.前端 接口的responseType设置成blob