Returning an Image or a File with Spring
Last Updated :
07 Apr, 2025
In web development, it is common for servers to send various types of content to clients, including static and dynamic data, images, and files. The Spring Framework provides powerful tools to handle these requirements efficiently, allowing developers to return images and files directly from endpoints.
Spring Boot simplifies sending files and images to the client through HTTP responses by using specific return types and annotations. The key concept involves setting the correct response headers and content type to inform the browser about the type of data being sent.
Key terminologies:
- Resources: Data types in Spring that abstract access to files and other low-level resources. Spring provides various implementations like UrlResource and ClassPathResource for accessing resources easily.
- ResponseEntity: A type in Spring MVC for handling complete HTTP responses, including status codes, headers, and content. It's used to configure responses sent back to clients.
- MediaType: Represents media types in HTTP communications, such as JSON or JPEG. It's used to set the Content-Type header in HTTP responses.
- Controller: A class in Spring MVC that handles incoming HTTP requests. It processes requests using methods annotated with @GetMapping or @PostMapping.
- Path: Represents file or directory paths in a system-independent way. It's part of Java's NIO package, offering more functionality than the traditional File class.
- Content-Type: An HTTP header indicating the media type of resources being sent to clients. It helps clients interpret received resources correctly.
Project Implementation to Return an Image or a File in Spring
Below are the implementation steps to return an Image or a File in Spring.
Step 1:
Create a new Spring Boot project using Spring Initializr with the specified dependencies below,
Dependencies:
- Spring Web
- Spring DevTools
- Lombok
After creating the project, the folder structure resembles the image below.
Step 2: Resource Image
We will save the sample image at the location specified below:
Go to src > java > resources > static > images > imageexample.png and save the sample image.
Step 3: Resource pdf
We will save the sample pdf at the location of the below path.
Go to src > java > resources > static > images > pdfexample.pdf and save the sample pdf link.
Step 4: Create the Image Controller class
Now, we will create the image controller class following the below path.
Go to src > org.example.springfiledemo > FileController and put the below code.
Java
package org.example.springfiledemo;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class FileController {
// Endpoint to serve image file
@GetMapping("/image")
public ResponseEntity<Resource> getImage() throws Exception {
// Path to the image file
Path path = Paths.get("src/main/resources/static/imageexample.png");
// Load the resource
Resource resource = new UrlResource(path.toUri());
// Return ResponseEntity with image content type
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_JPEG)
.body(resource);
}
// Endpoint to serve PDF file
@GetMapping("/file")
public ResponseEntity<Resource> getFile() throws Exception {
// Path to the PDF file
Path path = Paths.get("src/main/resources/static/pdfexample.pdf");
// Load the resource
Resource resource = new UrlResource(path.toUri());
// Return ResponseEntity with PDF content type
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.body(resource);
}
}
Step 5: Main Class
No need to change the main class of the application.
Java
package org.example.springfiledemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringFileDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringFileDemoApplication.class, args);
}
}
Step 6: Run the Application
Once we run the application, the project will run at port number 8080.
Output:
1. Image Endpoint:
http://localhost:8080/image
When we open above URL in browser, we will see the below image as result.
2. Pdf Endpoint:
http://localhost:8080/file
When we open above URL in browser, we will see the below pdf as result.
Similar Reads
Returning Image/Media Data with Spring MVC
Spring MVC is a popular framework to build web applications in Java. One of the common requirements in web development is handling image or media data such as pictures, videos, or audio files. In Spring MVC, handling image or media data involves configuring a controller to receive requests for speci
3 min read
Spring Boot - AOP After Returning Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
5 min read
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTf
7 min read
Inject a Map from a YAML File With Spring
Spring Framework provides a powerful way to configure applications using external configuration files. YAML (YAML Ain't Markup Language) is a popular format for configuration files due to its readability and ability to represent complex data structures easily. In this article, we will explore how to
4 min read
Spring @RequestMapping Annotation with Example
The @RequestMapping annotation in Spring MVC is one of the most important annotations used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to the handler method
4 min read
Spring @Required Annotation with Example
Spring Annotations provide a powerful way to configure dependencies and implement dependency injection in Java applications. These annotations act as metadata, offering additional information about the program. The @Required annotation in Spring is a method-level annotation used in the setter method
5 min read
Returning an HTML Page From a RESTful Controller in Spring Boot
In Spring Boot applications, RESTful controllers are commonly used to handle HTTP requests and return appropriate responses. These responses are typically in JSON or XML format. However, sometimes there is a need to return HTML pages, which the server can dynamically generate. In Spring Boot, we can
3 min read
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
Spring - Setter Injection with Non-String Map
In Spring Framework, Dependency Injection (DI) is a core concept that allows objects to be injected into one another, reducing tight coupling. Setter-based Dependency Injection (SDI) is a technique where dependencies are injected through setter methods. In this article, we will explore how to perfor
4 min read
Get the Response Body in Spring Boot Filter
In a Spring Boot application, filters can be used to intercept requests and responses, allowing you to manipulate them before reaching the controller or after the response is generated. A common requirement is capturing or logging the response body in the Spring Boot filter, especially for monitorin
5 min read