Springmvc實現檔案下載2種實現方法
阿新 • • 發佈:2020-03-09
使用springmvc實現檔案下載有兩種方式,都需要設定response的Content-Disposition為attachment;filename=test2.png
第一種可以直接向response的輸出流中寫入對應的檔案流
第二種可以使用 ResponseEntity<byte[]>來向前端返回檔案
一、使用response
@RestController @RequestMapping("/download") public class DownloadController { @RequestMapping("/d1") public ResultVo<String> downloadFile(HttpServletResponse response){ String fileName="test.png"; try { //獲取頁面輸出流 ServletOutputStream outputStream = response.getOutputStream(); //讀取檔案 byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\my-study\\test2.png")); //向輸出流寫檔案 //寫之前設定響應流以附件的形式開啟返回值,這樣可以保證前邊開啟檔案出錯時異常可以返回給前臺 response.setHeader("Content-Disposition","attachment;filename="+fileName); outputStream.write(bytes); outputStream.flush(); outputStream.close(); return ResultVoUtil.success("success"); } catch (IOException e) { return ResultVoUtil.error(e); } } }
推薦使用這種方式,這種方式可以以json形式給前臺返回提示資訊。
二、使用ResponseEntity
@Controller @RequestMapping("/download2") public class DownloadController2 { private final static Logger logger= LoggerFactory.getLogger(CategoryDataController.class); @GetMapping("/d2") public ResponseEntity<byte[]> download2(){ //獲取檔案物件 try { byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\my-study\\bill-admin\\test2.png")); HttpHeaders headers=new HttpHeaders(); headers.set("Content-Disposition","attachment;filename=test2.png"); ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,headers,HttpStatus.OK); return entity; } catch (IOException e) { logger.error("下載出錯:",e); return null; } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。