SpringMVC使用ResponseEntity实现下载文件
- 文件加载到内存中,作为响应体
- 设置好响应头,响应参数。
- 将以上参数赋值到ResponseEntity对象中,将ResponseEntity对象返回。
举例,一个方法搞定
@RequestMapping("/downloadFile2")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
// 需要下载的文件
File file = new File("d:/tools/t1.jpg");
byte[] body = null;
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
总结: 返回一个 ResponseEntity
对象即可实现文件下载。
项目打包 提取码:4cwn
环境:eclipse