采用流的方式下载文件,有以下优点:
1、存在数据库的文件不需生成一个文件到服务器,节约服务器空间,也省去了清理服务器文件的工作。
2、存在服务器或FTP服务器的文件进行下载,不需要暴露文件的地址
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response){
String id=request.getParameter("id");
HttpHeaders headers = new HttpHeaders();
CfFeedBackAttachment file=null;
String name="";
try {
file=commonReimService.get(CfFeedBackAttachment.class, Integer.parseInt(id));
name = URLEncoder.encode(file.getName(), "UTF-8");
headers.setContentDispositionFormData("attachment", name);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(file.getFfile(), headers, HttpStatus.OK);
return entity;
}