Downloading Files from Spring Boot REST Services
In Spring Boot, downloading a file from a REST service is often necessary. Here's a detailed explanation of how to implement this functionality:
Method 1: Using InputStreamResource
<code class="java">@RequestMapping(path = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> download(String param) throws IOException { // ... InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); }</code>
<code class="java">@RequestMapping(path = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> download(String param) throws IOException { // ... Path path = Paths.get(file.getAbsolutePath()); ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path)); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); }</code>
The above is the detailed content of How to Download Files from Spring Boot REST Services?. For more information, please follow other related articles on the PHP Chinese website!