Home > Java > javaTutorial > body text

How to Download Files from Spring Boot REST Services?

Susan Sarandon
Release: 2024-10-29 04:53:29
Original
237 people have browsed it

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>
Copy after login
<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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template