前端页面使用 Thymeleaf 实现 Excel 文件下载
前端页面中,可以使用<a>标签来创建一个超链接,通过设置href属性来指定下载文件的路径。在 Thymeleaf 模板中,可以使用${...}表达式来引用后端变量,如下所示:
<a th:href='@{/static/excel-file.xlsx}' download>下载Excel文件</a>
其中,@{/static/excel-file.xlsx}表示静态资源文件夹下的excel-file.xlsx文件路径,download属性表示点击链接后自动下载文件。
在后端中,可以使用 Spring Boot 提供的ResourceLoader来加载静态资源文件,如下所示:
@Autowired
private ResourceLoader resourceLoader;
@RequestMapping("/static/excel-file.xlsx")
public ResponseEntity<Resource> downloadExcelFile() throws IOException {
Resource resource = resourceLoader.getResource("classpath:static/excel-file.xlsx");
InputStream inputStream = resource.getInputStream();
ByteArrayResource byteArrayResource = new ByteArrayResource(IOUtils.toByteArray(inputStream));
return ResponseEntity.ok()
.contentLength(byteArrayResource.contentLength())
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(byteArrayResource);
}
在上述代码中,ResourceLoader会自动查找 classpath 下的静态资源文件夹,然后通过getResource方法获取指定文件的Resource对象。接着,将Resource对象中的数据流转换为字节数组,创建一个ByteArrayResource对象。最后,将ByteArrayResource对象封装到ResponseEntity中,设置响应头信息,返回给前端。
原文地址: https://www.cveoy.top/t/topic/ohlg 著作权归作者所有。请勿转载和采集!