使用spring提供的 ResponseEntity 进行文件下载
@RequestMapping("/downloadFile.do")
public ResponseEntity<byte[]> downloadFile(String fileName) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="+fileName);
String downLoadPath = "F:/upload/"+fileName;
InputStream in = new BufferedInputStream(new FileInputStream(downLoadPath));
byte[] b = new byte[in.available()];
in.read(b);
in.close();
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(b,headers,status);
return responseEntity;
}
<a href="downloadFile.do?fileName=img.png">点击下载</a>
原始方式:
@ResponseBody
@RequestMapping("/downloadFile")
public byte[] testDownload(HttpServletResponse response,String fileName) throws IOException{
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
String downLoadPath = "F:/upload/"+fileName;
InputStream in = new BufferedInputStream(new FileInputStream(downLoadPath));
byte[] b = new byte[in.available()];
in.read(b);
in.close();
return b;
}
- 两种方式都是使用输入输出流实现下载,没什么区别。
- 重点是要记得设置
"Content-Disposition","attachment;filename=web.xml"
请求头,浏览器才能认得这是一个下载
- 无论是哪一种方式,他们都是要将文件读到字节数组中
第一种方式,使用了ResponseEntity,这是spring封装的响应实体。我们定义好响应信息,然后丢进去就行了。
第二种方式,文件读到字节数组后,利用@responseBody注解将这个字节数组丢到相应信息的body中。