前端实现excel和word下载 不需要下载按钮点击链接直接下载 静态资源里有excel和word文件 前端用thymeleaf后端用springboot
- 在前端页面中添加一个链接,链接到后端接口,例如:
<a href="/download/excel" target="_blank">下载Excel文件</a>
<a href="/download/word" target="_blank">下载Word文件</a>
- 在后端中添加两个接口,一个用于下载Excel文件,一个用于下载Word文件,例如:
@GetMapping("/download/excel")
public void downloadExcel(HttpServletResponse response) throws Exception {
String fileName = "example.xlsx";
InputStream inputStream = getClass().getResourceAsStream("/static/" + fileName);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
@GetMapping("/download/word")
public void downloadWord(HttpServletResponse response) throws Exception {
String fileName = "example.docx";
InputStream inputStream = getClass().getResourceAsStream("/static/" + fileName);
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
- 打开浏览器,点击链接即可直接下载文件
原文地址: https://www.cveoy.top/t/topic/fsSp 著作权归作者所有。请勿转载和采集!