Spring Boot File Download Guide

In Spring Boot, you can download a file using the following methods:

  1. A byte array wrapped in a response entity.
@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. Resource which is a stream of input data
  2. a response entity containing an input stream resource
@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);
}

Both of these methods can be used for downloading files, the specific choice between them depends on your needs and preferences.

bannerAds