Spring MVC 的文件下載
阿新 • • 發佈:2017-09-17
中文名 adf attach formdata eat images mediatype alt 下載方式
在看Spring MVC文件下載之前請先看Spring MVC文件上傳
地址:http://www.cnblogs.com/dj-blog/p/7535101.html
文件下載比較簡單,在超鏈接中指定文件下載的文件名就可以了。
springMVC提供了一個ResponseEntity類型,可以方便的定義返回的HttpHeads和HttpStatus。
在FileUploadController中加入下面這個controller
@RequestMapping("/download") public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,Model model) throws Exception{ //下載文件路徑 String path = request.getServletContext().getRealPath("/images/"); File file = new File(path+File.separator+filename); HttpHeaders headers = new HttpHeaders(); //下載顯示的文件名,解決中文名字亂碼問題 String downloadFileName = newString(filename.getBytes("utf-8"),"iso-8859-1"); //通知瀏覽器已下載方式打開圖片 headers.setContentDispositionFormData("attachment", downloadFileName); //二進制數據下載 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED); }
然後就可以部署項目運行,可以看到如下結果
Spring MVC 的文件下載