在SpringMVC中,提供了两种方式进行文件下载
- ResponseEntity
- @ResponseBody注解
前端请求界面:
<a href="${pageContext.request.contextPath }/testFileDownLoad">Download file</a>
第一种方式实现:
@RequestMapping("testFileDownLoad")
public ResponseEntity<byte[]> testFileDownload(HttpServletRequest request)throws Exception{
//获取application对象
ServletContext application = request.getServletContext();
InputStream input = application.getResourceAsStream("/file/abc.txt");
byte[] b = new byte[input.available()];
input.read(b);
//设置响应头
HttpHeaders header = new HttpHeaders();
header.add("Content-Disposition", "attachment;filename=abc.txt");
//返回ResponseEntity
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(b, header, HttpStatus.OK);
return responseEntity;
}
第二种方式实现:
@ResponseBody
@RequestMapping("testFileDownLoad")
public byte[] testFileDownload(HttpServletRequest request,HttpServletResponse response)throws Exception{
//获取application对象
ServletContext application = request.getServletContext();
InputStream input = application.getResourceAsStream("/file/abc.txt");
byte[] b = new byte[input.available()];
input.read(b);
//设置响应头
response.addHeader("Content-Disposition", "attachment;filename=abc.txt");
return b;
}
小结
对于文件下载,最重要的是设置响应头,两种方式的不同之处也是在于设置响应头的方式不同。