從 Spring Boot REST 服務下載檔案
在 Spring Boot 中,通常需要從 REST 服務下載檔案。以下詳細說明如何實現此功能:
方法一:使用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>
以上是如何從 Spring Boot REST 服務下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!