Spring MVC 的文件下载

it2022-05-09  35

在看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 = new String(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); }

然后就可以部署项目运行,可以看到如下结果

 

转载于:https://www.cnblogs.com/dj-blog/p/7535340.html

相关资源:Spring Mvc下实现以文件流方式下载文件的方法示例

最新回复(0)