Home >Java >javaTutorial >How to Download Files from Spring Boot REST Services?

How to Download Files from Spring Boot REST Services?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 04:53:29298browse

How to Download Files from Spring Boot REST Services?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn