需求:根据前端传递的id查询数据库中相对于的文件路径,根据相对应路径将文件下载下来
注:下列代码中的注1、注2、注3、注4、注5代表需要更换的内容后可直接使用
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFile(@RequestParam(value="id") Long id)
throws Exception {
PlywoodInfo f = service.download(id); //注1
if(f==null){
return fail("文件不存在!");
}else{ //f.getPlywoodPath()为数据库中查到的文件路径 eg:D:/test
File _file = new File(f.getPlywoodPath());
if(!_file.exists()){
return fail("文件不存在!");
}
String startPath = f.getStartPath(); //注2
File startPathFile = new File(startPath); //注3
String finalFileName = URLEncoder.encode( startPathFile.getName() + ".xml","UTF-8"); //注4
FileSystemResource file = new FileSystemResource(f.getPlywoodPath());//注5
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", finalFileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
}
private ResponseEntity<InputStreamResource> fail(String msg){
String errorMsg = "<script language=\"javascript\">alert('"+msg+"');</script>";
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(errorMsg.getBytes("GBK"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE,"text/html;charset=UTF-8");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.TEXT_HTML)
.body(inputStreamResource);
}
注1:PlywoodInfo f = service.download(id); //这行代表表示根据id查询数据库中的内容
注2,注3和注4是给下载后的文件给一个名字、
如果有疑问可以私密,有不足地方可以说出来,谢谢!