springboot下載文件(使用流)


1.FileServiceImpl.java

/** * 下載文件 * * @param address * @param response * @throws IOException */ @Override public void downloadFile(String address, HttpServletResponse response) throws IOException { if (address.contains("%")) { try { address = URLDecoder.decode(address, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CyException("文件路徑有誤"); } } ServletOutputStream out = null; FileInputStream in = null; try { in = new FileInputStream(new File(address)); String[] dir = address.split("/"); String fileName = dir[dir.length - 1]; // 設置響應類型為html,編碼為utf-8,處理相應頁面文本顯示的亂碼 response.setContentType("application/octet-stream"); // 設置文件頭:最后一個參數是設置下載文件名 response.setHeader("Content-disposition", "attachment;filename=" + fileName); out = response.getOutputStream(); // 讀取文件流 int len = 0; byte[] buffer = new byte[1024 * 10]; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); } catch (FileNotFoundException e) { throw new CyException("文件路徑有誤"); } finally { response.flushBuffer(); try { out.close(); in.close(); } catch (NullPointerException e) { throw new CyException("responseFileStream stream close() error:NullPointerException" + e.toString()); } catch (Exception e) { throw new CyException("responseFileStream stream close() error:" + e.toString()); } } } 

2.FileController.java

@RequestMapping(value = "/downloadFile", method = RequestMethod.GET) @ResponseBody @Validated public void downloadFile(@NotBlank @RequestParam(value = "address") String address, HttpServletResponse response) throws IOException { fileService.downloadFile(address, response); } 

 

 
 轉自:https://www.cnblogs.com/xian-yu/p/13267312.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM