Controller層
@GetMapping("download") @ApiOperation("下載模板") public void downLoadFile(@RequestParam String type, HttpServletResponse response) { String fileName = "house".equals(type) ? "附件一:xxx.xlsx" : "developer".equals(type) ? "附件二:xxx.xlsx" : "intention".equals(type) ? "附件三:xxx.xlsx":""; try { WebUtil.downloadFile(response, fileName, "listData/"); //此處listData文件下存放excel模板以供下載 } catch (IOException e) { log.error("[清單管理]", e); } }
WebUtil公用方法
/** * @return void * @throws * @description linux中獲取文件路徑有問題,建議用此種方法進行下載 * @Param [response, fileName] */ public static void downloadFile(HttpServletResponse response, String fileName, String filePath) throws IOException { if (StringUtils.isNotBlank(fileName)) { InputStream stream = WebUtil.class.getClassLoader().getResourceAsStream(filePath + fileName); @Cleanup BufferedInputStream bis = new BufferedInputStream(stream); writeResponse(response, fileName, bis); } }
/** * @return void * @throws * @description 向response中寫入文件 * @Param [response, fileName, bis] */ private static void writeResponse(HttpServletResponse response, String fileName, BufferedInputStream bis) throws IOException { response.setCharacterEncoding("utf-8"); // 設置強制下載不打開application/force-download response.setContentType("application/octet-stream"); //設置文件名稱 response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8")); OutputStream os = response.getOutputStream(); byte[] buffer = new byte[1024]; int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } }