當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot+thymeleaf实现文件下载(已实践,全流程)
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot+thymeleaf实现文件下载(已实践,全流程)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景
在頁面中點擊模板,實現(xiàn)excel模板的下載。
效果
實現(xiàn)
thymeleaf頁面代碼
<button id="dowloadBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 模板下載</button>在當(dāng)前頁面引入js文件
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"th:replace="layout/layout(title='數(shù)據(jù)',cssPaths='/public/css/plugins/jsTree/style.min.css',jsPaths='/modular/receiveOrder/wmsReceiveOrder.js')">js中
//模板下載按鈕點擊事件$("#dowloadBtn").click(function () {templateDowload()});在實現(xiàn)方法中
//EXCel模板下載 function templateDowload(){window.location.href="/wmsReceiveOrder/downloadOnlineLearnMaterials"; }請求到后臺Controller
?@Description("模板下載")@RequestMapping("/downloadOnlineLearnMaterials")public String downloadFile(HttpServletRequest request, HttpServletResponse response) {String fileName = "template.xlsx";// 設(shè)置文件名,根據(jù)業(yè)務(wù)需要替換成要下載的文件名if (fileName != null) {//設(shè)置文件路徑String realPath = configProperties.getExcelTemplateDpwloadPath();//這里使用配置類配置文件路徑File file = new File(realPath , fileName);if (file.exists()) {response.setContentType("application/force-download");// 設(shè)置強制下載不打開response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設(shè)置文件名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();
是使用的配置類配置文件路徑,這里可以根據(jù)具體業(yè)務(wù)修改,可以改為固定路徑。
具體怎樣使用配置文件以及配置類實現(xiàn)文件上傳下載路徑的修改
參照:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/88786320
比如這里的模板文件,路徑為
總結(jié)
以上是生活随笔為你收集整理的SpringBoot+thymeleaf实现文件下载(已实践,全流程)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot中使用yml配置文件
- 下一篇: Java在MVC开发模式中使用try-c