1. 使用FileSystemResource,以文件系统的绝对路径的方式访问静态资源

FileSystemResource file= new FileSystemResource("c:\\xx\\xxx\\1.txt");
@GetMapping("/down")
public ResponseEntity<FileSystemResource> download(@RequestParam("uri") String uri) throws IOException {
File file = new File(uri);
if (!file.isFile()) {
throw new ServiceException("文件不存在");
}

String filename = FilenameUtils.getName(uri);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
HttpStatus status = HttpStatus.OK;
return new ResponseEntity<>(new FileSystemResource(file), headers, status);
}

2. 使用缓存流,边读边写

@GetMapping("/down")
public void download(@RequestParam("uri") String uri, HttpServletResponse response) {
File file = new File(uri);
if (!file.isFile()) {
throw new ServiceException("文件不存在");
}

String filename = FilenameUtils.getName(uri);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
FileCopyUtils.copy(bufferedInputStream, bufferedOutputStream);
} catch(Exception e){

} finally {

}
}

@GetMapping("/down")
public void download(@RequestParam("uri") String uri, HttpServletResponse response) {
File file = new File(uri);
if (!file.isFile()) {
throw new ServiceException("文件不存在");
}

String filename = FilenameUtils.getName(uri);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {


byte[] buffer_ = new byte[1024];

int n = bufferedInputStream.read(buffer_);
while(n != -1){
bufferedOutputStream.write(buffer_);
n = bufferedInputStream.read(buffer_);
}

bufferedInputStream.close();
bufferedOutputStream.close();

} catch(Exception e){

} finally {

}

}
3. 文件存储到oss或者是七牛云,绕过服务器下载等方式

 

参考:

https://my.oschina.net/pwh19920920/blog/4699776?tdsourcetag=s_pctim_aiomsg


————————————————
版权声明:本文为CSDN博主「shiboyuan0410」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/shiboyuan0410/article/details/115209291

相关文章:

  • 2021-08-21
  • 2022-12-23
  • 2022-12-23
  • 2021-08-24
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-25
  • 2021-09-17
  • 2021-04-29
  • 2022-02-20
  • 2021-06-06
  • 2021-05-30
  • 2022-12-23
相关资源
相似解决方案