@GetMapping("/download/{fileName}")
@ResponseBody
public ResponseEntity<Object> downloadFile(@PathVariable(name = "fileName") String fileName) throws FileNotFoundException {
File file = new File(fileUploadRootDir + fileName);
if (!file.exists())
{
return new ResponseEntity<Object>("{\"code\": \"00002\", \"info\":\"File Not Found!\"}", HttpStatus.BAD_REQUEST);
}
InputStreamResource resource = new InputStreamResource( new FileInputStream( file ) );
HttpHeaders headers = new HttpHeaders();
headers.add ( "Content-Disposition",String.format("attachment;filename=\"%s",fileName));
headers.add ( "Cache-Control","no-cache,no-store,must-revalidate" );
headers.add ( "Pragma","no-cache" );
headers.add ( "Expires","0" );
ResponseEntity<Object> responseEntity = ResponseEntity.ok()
.headers ( headers )
.contentLength ( file.length ())
.contentType(MediaType.parseMediaType ( "application/octet-stream" ))
.body(resource);
return responseEntity;
}
以上的代码可以用来下载文件,fileUploadRootDir 这个变量是文件的存储路径。
本文介绍了如何在SpringBoot应用中实现文件下载功能,重点在于使用fileUploadRootDir变量设置的文件存储路径来完成文件的读取和发送到客户端的过程。
2014

被折叠的 条评论
为什么被折叠?



