SpringBootでファイルをダウンロードする方法は何ですか?

Spring Bootでは、ファイルをダウンロードするために以下の方法を使用することができます。

  1. byte[]を返すResponseEntity
@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. 入力ストリームリソース
  2. InputStreamResourceを含むResponseEntity
@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);
}

どちらの方法もファイルをダウンロードするために使用することができますが、具体的にはあなたのニーズや好みによってどちらの方法を選択するか決まります。

bannerAds