欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

SpringBoot+thymeleaf实现文件下载(已实践,全流程)

发布时间:2025/3/19 javascript 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 SpringBoot+thymeleaf实现文件下载(已实践,全流程) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

场景

在页面中点击模板,实现excel模板的下载。

效果

实现

thymeleaf页面代码

<button id="dowloadBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 模板下载</button>

在当前页面引入js文件

<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"th:replace="layout/layout(title='数据',cssPaths='/public/css/plugins/jsTree/style.min.css',jsPaths='/modular/receiveOrder/wmsReceiveOrder.js')">

js中

//模板下载按钮点击事件$("#dowloadBtn").click(function () {templateDowload()});

在实现方法中

//EXCel模板下载 function templateDowload(){window.location.href="/wmsReceiveOrder/downloadOnlineLearnMaterials"; }

请求到后台Controller

 @Description("模板下载")@RequestMapping("/downloadOnlineLearnMaterials")public String downloadFile(HttpServletRequest request, HttpServletResponse response) {String fileName = "template.xlsx";// 设置文件名,根据业务需要替换成要下载的文件名if (fileName != null) {//设置文件路径String realPath = configProperties.getExcelTemplateDpwloadPath();//这里使用配置类配置文件路径File file = new File(realPath , fileName);if (file.exists()) {response.setContentType("application/force-download");// 设置强制下载不打开response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名byte[] buffer = new byte[1024];FileInputStream fis = null;BufferedInputStream bis = null;try {fis = new FileInputStream(file);bis = new BufferedInputStream(fis);OutputStream os = response.getOutputStream();int i = bis.read(buffer);while (i != -1) {os.write(buffer, 0, i);i = bis.read(buffer);}System.out.println("success");} catch (Exception e) {e.printStackTrace();} finally {if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}}return null;}

 

其中String realPath = configProperties.getExcelTemplateDpwloadPath();

是使用的配置类配置文件路径,这里可以根据具体业务修改,可以改为固定路径。

具体怎样使用配置文件以及配置类实现文件上传下载路径的修改

参照:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/88786320

比如这里的模板文件,路径为

总结

以上是生活随笔为你收集整理的SpringBoot+thymeleaf实现文件下载(已实践,全流程)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。