使用 SpringBoot 从资源中下载文件

Jav*_*rot 1 java spring-boot

如何从 reosurces/folderX/file.txt 获取文件

@PostMapping(value = "/uploadFile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<Resource> uploadFile(@RequestParam("file") MultipartFile file) {
    /* 
     * FIRST I upload file
     * Next, I need to return different file in this request 
     */ 
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "file.txt + "\"").body();
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以像这样提供资源:

@GetMapping(value = "file")
public ResponseEntity<Resource> file() {

  Resource resource = new ClassPathResource("folderX/file.txt");

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"file.txt\"");

  return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)