温馨提示×

springboot下载文件的方法是什么

小亿
84
2024-02-04 09:13:26
栏目: 编程语言

在Spring Boot中,您可以使用以下方法来下载文件:

  1. 使用ResponseEntity<byte[]>返回文件数据和相关的HTTP头信息。
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
    // 从文件系统或其他来源获取文件
    File file = new File("path/to/file");

    // 将文件读入字节数组
    byte[] fileContent = Files.readAllBytes(file.toPath());

    // 设置HTTP头信息
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", file.getName());

    // 返回ResponseEntity对象
    return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}
  1. 使用InputStreamResourceResponseEntity<InputStreamResource>返回文件的输入流和相关的HTTP头信息。
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
    // 从文件系统或其他来源获取文件
    File file = new File("path/to/file");

    // 创建文件输入流
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    // 设置HTTP头信息
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", file.getName());

    // 返回ResponseEntity对象
    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .body(resource);
}

这两种方法都可以用来下载文件,具体使用哪种方法取决于您的需求和偏好。

0