Springmvc實(shí)現(xiàn)文件下載2種實(shí)現(xiàn)方法
使用springmvc實(shí)現(xiàn)文件下載有兩種方式,都需要設(shè)置response的Content-Disposition為attachment;filename=test2.png
第一種可以直接向response的輸出流中寫入對(duì)應(yīng)的文件流
第二種可以使用 ResponseEntity<byte[]>來(lái)向前端返回文件
一、使用response
@RestController @RequestMapping("/download") public class DownloadController { @RequestMapping("/d1") public ResultVo<String> downloadFile(HttpServletResponse response){ String fileName="test.png"; try { //獲取頁(yè)面輸出流 ServletOutputStream outputStream = response.getOutputStream(); //讀取文件 byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\my-study\\test2.png")); //向輸出流寫文件 //寫之前設(shè)置響應(yīng)流以附件的形式打開(kāi)返回值,這樣可以保證前邊打開(kāi)文件出錯(cuò)時(shí)異常可以返回給前臺(tái) 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形式給前臺(tái)返回提示信息。
二、使用ResponseEntity
@Controller @RequestMapping("/download2") public class DownloadController2 { private final static Logger logger= LoggerFactory.getLogger(CategoryDataController.class); @GetMapping("/d2") public ResponseEntity<byte[]> download2(){ //獲取文件對(duì)象 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("下載出錯(cuò):",e); return null; } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Cache擴(kuò)展功能實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Spring Cache擴(kuò)展功能實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02性能調(diào)優(yōu)之java服務(wù)器容器調(diào)優(yōu)詳解
這篇文章主要介紹了java服務(wù)器容器調(diào)優(yōu),如果接口響應(yīng)時(shí)間超過(guò)了既定數(shù)據(jù),項(xiàng)目支撐不了這么大的請(qǐng)求,就需要對(duì)項(xiàng)目以及項(xiàng)目接口進(jìn)行數(shù)據(jù)庫(kù)、容器、緩存等方面的調(diào)優(yōu),文章中有詳細(xì)的代碼示例,需要的朋友可以參考一下2023-04-04解讀java?try?catch?異常后還會(huì)繼續(xù)執(zhí)行嗎
這篇文章主要介紹了解讀java?try?catch?異常后還會(huì)不會(huì)繼續(xù)執(zhí)行問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11微信公眾號(hào)獲取access_token的方法實(shí)例分析
這篇文章主要介紹了微信公眾號(hào)獲取access_token的方法,結(jié)合實(shí)例形式分析了java實(shí)現(xiàn)微信公眾號(hào)獲取access_token的相關(guān)原理、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2019-10-10Springboot整合EasyExcel實(shí)現(xiàn)Excel文件上傳方式
這篇文章主要介紹了Springboot整合EasyExcel實(shí)現(xiàn)Excel文件上傳方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07