温馨提示×

spring实现文件下载的方法是什么

小亿
340
2024-06-07 18:38:36
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Spring中实现文件下载可以使用以下方法:

  1. 使用 ResponseEntity 返回文件流:
@GetMapping("/downloadFile")
public ResponseEntity<Resource> downloadFile() {
    Resource resource = new FileSystemResource("path/to/file.txt");
    
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt");
    
    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(resource.contentLength())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}
  1. 使用 HttpServletResponse 输出文件流:
@GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {
    File file = new File("path/to/file.txt");
    
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt");
    response.setContentLength((int) file.length());
    
    try (
        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();
    ) {
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这两种方法都可以实现文件下载,第一种方法使用 ResponseEntity 返回文件资源,第二种方法直接使用 HttpServletResponse 输出文件流。您可以根据自己的需求选择其中一种方法来实现文件下载。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:springboot下载文件的方法是什么

0