基於此篇文章中的一些沒有註釋的相關問題,今天進行SpringMVC的檔案下載的更新:
新方法:
1.控制層,新建一個方法,返回值型別為ResponseEntity<byte[]>的方法,並在其函式的後面新增對應的後臺需要處理的引數,比如可以傳遞FIleName
/** * 檔案下載 * * @param id * @return */ @GetMapping("/download/") public ResponseEntity<byte[]> download(@PathVariable("id") String id) throws IOException { File file = xxxService.buildXlsFileById(id); return ResponseUtils.buildResponseEntity(file); }
2. 編寫service返回File檔案物件,從Service層中查詢資料庫操作,並查詢檔案真正的路徑位置,然後返回File物件
public File buildXlsById(String id){ //do something to find this file File file=new File("1.txt"); return file; }
3. 編寫ResponseUtils中的相關方法
/** * 構建下載類 * @param file * @return * @throws IOException */ public static ResponseEntity<byte[]> buildResponseEntity(File file) throws IOException { byte[] body = null; //獲取檔案 InputStream is = new FileInputStream(file); body = new byte[is.available()]; is.read(body); HttpHeaders headers = new HttpHeaders(); //設定檔案型別 headers.add("Content-Disposition", "attchement;filename=" + file.getName()); //設定Http狀態碼 HttpStatus statusCode = HttpStatus.OK; //返回資料 ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode); return entity; }
4.編寫相對應得URL即可
老方法
/** * 檔案下載 * @Description: * @param fileName * @param request * @param response * @return */ @RequestMapping("/download") public String downloadFile(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) { if (fileName != null) { String realPath = request.getServletContext().getRealPath( "WEB-INF/File/"); File file = new File(realPath, fileName); if (file.exists()) { response.setContentType("application/force-download");// 設定強制下載不開啟 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設定檔名 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) { // TODO: handle exception e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } return null; }