MVC——11 SpringMVC的文件下载

SpringMVC的文件下载

1.访问资源时相应头如果没有设置 Content-Disposition,浏览器默认按照 inline 值进行处理

注:inline 能显示就显示,不能显示就下载

2.只需要修改相应头中 Context-Disposition=”attachment;filename=文件名”

  1. attachment 下载,以附件形式下载
  2. filename=值就是下载时显示的下载文件名

3.实现步骤

  1. 导入 apatch 的两个 jar
    commons-fileupload-1.3.1.jar
    commons-io-2.2.jar
  2. 在 jsp 中添加超链接,设置要下载文件
    注:在 springmvc 中放行静态资源 files 文件夹
<a href="download?fileName=a.rar">下载</a>
  1. 编写控制器方法
@RequestMapping("download") 
public void download(String fileName,HttpServletResponse res,HttpServletRequest req) throws IOException{
//设置响应流中文件进行下载 
res.setHeader("Content-Disposition", "attachment;filename="+fileName);
//把二进制流放入到响应体中
ServletOutputStream os = res.getOutputStream(); 
String path = req.getServletContext().getRealPath("files"); 
System.out.println(path); File file = new File(path, fileName); 
byte[] bytes = FileUtils.readFileToByteArray(file); 
os.write(bytes); 
os.flush(); 
os.close(); 
}
发布了167 篇原创文章 · 获赞 15 · 访问量 6168

猜你喜欢

转载自blog.csdn.net/Re_view/article/details/100584545