最近在翻看笔记时,发现自己对SpringMVC文件下载这块有些遗忘,所以整理一些文件下载的相关内容
- 访问资源时相应头如果没有设置 Content-Disposition,浏览器默认按照 inline 值进行处理
- inline 能显示就显示,不能显示就下载.
- 需要修改相应头中 Context-Disposition=”attachment;filename=文件名”
- attachment 下载,以附件形式下载.
- filename=值就是下载时显示的下载文件名
@RequestMapping("download")
public void download(String
fileName,HttpServletResponse res,HttpServletRequest req) throws IOException{
String filname = "test.txt";
//设置响应流中文件进行下载
response.setHeader("Content-Disposition", "attachment;filename=" + filname);
//把二进制流放入到响应体中.
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();
}