Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

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

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@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);
}
Answer from fateddy on Stack Overflow
Top answer
1 of 7
269

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

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

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@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);
}
2 of 7
71

The below Sample code worked for me and might help someone.

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/app")
public class ImageResource {

    private static final String EXTENSION = ".jpg";
    private static final String SERVER_LOCATION = "/server/images";

    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(@RequestParam("image") String image) throws IOException {
        File file = new File(SERVER_LOCATION + File.separator + image + EXTENSION);

        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=img.jpg");
        header.add("Cache-Control", "no-cache, no-store, must-revalidate");
        header.add("Pragma", "no-cache");
        header.add("Expires", "0");

        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

        return ResponseEntity.ok()
                .headers(header)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

}
🌐
Javainuse
javainuse.com › spring › boot-file-download
Spring Boot File Download - Hello World Example
package com.javainuse; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootFileDownoad { public static void main(String[] args) { SpringApplication.run(SpringBootFileDownoad.class, args); } } Next define the controller for downloading the file -
🌐
CodeJava
codejava.net › frameworks › spring-boot › file-download-upload-rest-api-examples
Spring Boot File Download and Upload REST API Examples
November 16, 2023 - And it inserts 8 alphanumeric characters before the file name, so in the file download API it can identify a file based on an identifier.Finally, the method returns the fileCode which is then used in download URI field of the response body. Next, code a @RestController class to implement the file upload API as shown below: package net.codejava.upload; import java.io.IOException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springfram
🌐
o7planning
o7planning.org › 11765 › spring-boot-file-download
Spring Boot File Download Example | o7planning.org
package org.o7planning.sbdownload; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDownloadApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDownloadApplication.class, args); } } Write a method to return ResponseEntity. This object wraps the InputStreamResource object (which is data of the file downloaded by user). ... package org.o7planning.sbdownload.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOExceptio
🌐
DevGlan
devglan.com › spring-boot › spring-boot-file-upload-download
Uploading and Downloading Files with Spring Boot
While downloading multiple files, ... this purpose, we first need to create a zip file in spring boot and then set the content type as application/zip to download the zip file. Here, we will be using ZipOutputStream from java.util.zip package ...
🌐
Oodlestechnologies
oodlestechnologies.com › blogs › how-to-download-a-file-directly-from-url-in-spring-boot
How To Download A File Directly From URL In Spring Boot
February 14, 2020 - 2. Download File using InputStream to HttpServletResponse · To read files in java we can use Reader or Stream. But for text data Reader is the good option to use but for binary data, we should use Stream.
🌐
DEV Community
dev.to › nashmin_hasan › file-download-feature-in-spring-boot-co1
File Download Feature in Spring Boot - DEV Community
July 8, 2025 - When building backend applications, it’s common to allow users to download files they've previously uploaded — such as invoices, images, PDFs, or documents. In this post, we’ll walk through how to implement a download endpoint in a Spring Boot REST API.
Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › client-file-downloads-in-spring-boot-with-byte-streams-6ea8f6205bb4
File Downloads in Spring Boot with Byte Streams | Medium
August 7, 2025 - Spring Boot has strong support for streaming data to clients, and the mechanics behind that are built on Java’s file handling and HTTP output streams. When files are streamed instead of fully loaded, you keep memory use stable and avoid blocking other requests on the server. This section looks at how that works from the moment the request arrives to the point the browser starts receiving the content. Applications that offer downloadable content sometimes fall into the trap of reading the full file into a byte array before sending it.
🌐
Springcloud
springcloud.io › post › 2023-03 › springboot-download
File Downloading in Spring Boot Applications - Spring Cloud
March 15, 2023 - This article provides guidance on how to download a single file, download a Gzip-compressed file, and download multiple files through a zip archive in a Spring Boot application.
🌐
opencodez
opencodez.com › java › file-upload-and-download-in-java-spring-boot.htm
Simplest and Easy way to Upload and Download Files in Java with Spring Boot | opencodez
June 14, 2019 - This resource is later pushed to download via the controller. Now let us look at few controller methods which utilize above service class to achieve the functionality. Above method will kick off, when you upload a file from UI. The Spring controller receives a MultipartFile, which is then sent to storage service class.
🌐
Djamware
djamware.com › post › 68e1e24ccc093c00a5927365 › java-file-upload-and-download-with-spring-boot-rest-api
Java File Upload and Download with Spring Boot REST API
October 4, 2025 - In this section, you’ll create a REST endpoint that lets users download files previously uploaded to the local filesystem. Let’s extend the existing FileUploadController by adding a new method for downloading files. File: src/main/java/com/djamware/file_upload_download/controller/FileUploadController.java ... import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import java.net.MalformedURLException;
🌐
Java Guides
javaguides.net › 2020 › 04 › spring-boot-file-upload-download-rest-api-example.html
Spring Boot File Upload / Download Rest API Example
March 27, 2023 - In this tutorial, we will learn how to upload and download a file using Spring Boot RESTful API. Uploading and downloading files are very common tasks for which developers need to write code in their applications.
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - In this tutorial, we’ll see several methods that we can use to download a file. We’ll cover examples ranging from the basic usage of Java IO to the NIO package as well as some common libraries like AsyncHttpClient and Apache Commons IO.
🌐
DZone
dzone.com › coding › frameworks › java spring boot rest api to upload/download file on server
Java Spring Boot Rest API to Upload/Download File
May 1, 2020 - Response: Will return the file in attachment along with content-type and other details. (If file not found for that user it will return 404 Not found code) ... UploadFileResponse: To send the response back when the upload is successful. ... In order to secure your API with Spring Basic Auth add below the class.
🌐
Medium
medium.com › @samarthgvasist › springboot-file-handling-file-download-part-2-7e44702a9bf
Springboot File Handling: File Download (Part -2) | by Samarth G Vasist | Medium
October 5, 2022 - Before reading this article, I would highly recommend you all to go through the part -1 of this series titled Springboot File Handling- File Upload (Part -1) File download is the process of transmission of a file from a server to a user device.
🌐
HowToDoInJava
howtodoinjava.com › home › spring mvc › spring mvc file download controller example
Spring MVC File Download Controller Example
May 28, 2024 - In this Spring Boot MVC download file controller example, learn to create the handler method and prevent hot linking of the download URLs.
🌐
Medium
medium.com › @AlexanderObregon › how-to-handle-file-uploads-and-downloads-with-spring-boot-84638463fd6f
Manage File Uploads & Downloads in Spring Boot | Medium
April 17, 2024 - Learn how to manage file uploads and downloads using Spring Boot, including setups and essential security measures for strong application performance.
🌐
GeeksforGeeks
geeksforgeeks.org › springboot › spring-mvc-download-file-controller
Spring MVC - Download File Controller - GeeksforGeeks
July 23, 2025 - Here we have used Spring Boot for ... the file. Step 1: Create a Spring Stater Project using your favorite IDE (Reference) Step 2: In the main package, create one Java class for the Download File Controller...