Home > OS >  Download a file from resources with SpringBoot
Download a file from resources with SpringBoot

Time:12-14

How can I get a file from 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();
}

CodePudding user response:

You can serve a resource like this:

@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);
}
  • Related