1.后端java springboot
背景:文件是以xls类型的文件。
第一步:添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14/version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
其他公共包自行添加
第二步:代码
@PostMapping("/downLoad")
@ResponseBody
public void downLoad(@RequestParam(value = "path") String path,
HttpServletResponse response) {
String fileName = "fileName.xls"
try{
//注意这里是处理xls ,用的是HSSFWorkbook,path 是文件的存储路径
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(path));
OutputStream fos = null;
fos = response.getOutputStream();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8")
response.setHeader("Content-Disposition",fileName);
response.setHeader("filename",fileName);
response.setHeader("Access-Control-Expose-Headers","filename");
wb.write(fos);
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
2.后端vue+elementUI
//页面
<el-button @click="downLoadFun(scope.row.path)"></el-button>
//script方法
downLoadFun(path){
const url = hostUrl + path;
axios({
method:"post",
url:url,
params:{
path:path
},
responseType:"blob",
headers:{
"X-Requested-With":"XMLHttpRequest"
}
}).then(res => {
const link = document.createElement("a");
let blob = new Blob([res.data],{type:"application/vnd.ms-excel"});
link.style.display="none";
const blobUrl = (link.href = URL.createObjectURL(blob));
const filename = res.header.filename;
link.setAttribute("download",filename);
link.click();
URL.revokeObjectURL(blobUrl);
document.body.removeChild(link);
}).catch(error => {
this.$message.error("Download exception!");
})
}