1. 程式人生 > 其它 >SpringBoot+thymeleaf實現模板檔案下載

SpringBoot+thymeleaf實現模板檔案下載

1.配置檔案:
    pom.xml中新增依賴:
    <!-- thymeleaf模版 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    application.yml檔案中新增要下載的模板檔案存放地址

    
    新增讀取配置的模板存放地址

2.前臺程式碼
    <a href="javascript:downTemple()" style="color:#1c99ef;text-decoration:underline;">下載模板</a>

  function downTemple(){
       window.location.href="/UserController/downTemple";
   }
3.後臺程式碼
     @RequestMapping(value = "/downTemple")
    public String downTemple(HttpServletResponse response, RedirectAttributes redirectAttributes) {
         String fileName 
= "使用者資訊模板.xlsx";// 設定檔名,根據業務需要替換成要下載的檔名 if (fileName != null) { //設定檔案路徑 String realPath = configProperties.getExcelTemplateDpwloadPath();//這裡使用配置類配置檔案路徑 File file = new File(realPath , fileName); if (file.exists()) { try { response.setContentType(
"application/force-download");// 設定強制下載不開啟 fileName =java.net.URLDecoder.decode(fileName,"UTF-8"); response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("GB2312"),"iso8859-1"));// 設定檔名 中文要編碼後才可以 } catch (UnsupportedEncodingException e1) { // TODO 自動生成的 catch 塊 e1.printStackTrace(); } 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); } } 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; }