日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

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

發布時間:2025/3/19 javascript 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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实现文件下载(已实践,全流程)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。