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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐