springboot 大文件下载

1 篇文章 0 订阅

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

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值