1. 程式人生 > >springboot 應用中靜態資源下載

springboot 應用中靜態資源下載

pin 直接 需求 stat col map source ade resource

一. 場景介紹

  • Excel模板靜態資源在,應用中的static文件夾中,文件名稱包含中文;
  • 需求:頁面直接訪問下載Excel模板.

二.目錄結構

  技術分享圖片

三.後臺代碼

 1    @GetMapping("/downloadTemplateForUserTest")
 2     @ResponseBody
 3     public void downloadLocal(HttpServletResponse response) throws Exception {
 4         /** 獲取靜態文件的路徑 .*/
 5         String path = ResourceUtils.getURL("classpath:").getPath() + "static/js/CRM_客戶_導入模板.xlsx";
6 7 /** 獲取文件的名稱 . */ 8 String fileName = path.substring(path.lastIndexOf("/") +1); 9 File file = new File(path); 10 if (!file.exists()){ 11 logger.error("路徑有誤,文件不存在!"); 12 } 13 14 /** 將文件名稱進行編碼 */ 15 response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
16 response.setContentType("content-type:octet-stream"); 17 BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); 18 OutputStream outputStream = response.getOutputStream(); 19 byte[] buffer = new byte[1024]; 20 int len; 21 while
((len = inputStream.read(buffer)) != -1){ /** 將流中內容寫出去 .*/ 22 outputStream.write(buffer ,0 , len); 23 } 24 inputStream.close(); 25 outputStream.close(); 26 }

2019-04-19 16:49:19 -- 1.0v

springboot 應用中靜態資源下載