Returning Image/Media Data with Spring MVC
Last Updated :
20 May, 2024
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 specific resources and then serving those resources to clients. We will use the @Controller annotation to define the controller class, and it can utilize methods annotated with @RequestMapping to map incoming requests to appropriate handlers. We will load the image from the file system or database within these handlers and return it as the response.
Key Terminologies:
- Spring MVC: Spring MVC, short for Model-View-Controller, is a framework within the Spring Framework for building web applications and RESTful web services in Java.
- Controller: It handles incoming HTTP requests, processes them, and generates the appropriate response. It's typically annotated with
@Controller
and contains methods annotated with @RequestMapping
or other handler annotations. RequestMapping:
This
is an annotation used in Spring MVC to map HTTP requests to specific handler methods within the controller class. It allows developers to define URL patterns that trigger the execution of particular methods.ResponseEntity:
It
is a class in Spring MVC representing the HTTP response. It allows developers to control the HTTP status code, headers, and body of the response returned by the controller method.MediaType
: It
is an enum class in the Spring Framework representing standard MIME types. It's commonly used to specify the content type of HTTP requests and responses, such as JSON, XML, HTML, or image formats like JPEG and PNG.
Implementation to Return Image/Media Data with Spring MVC
Step 1: Create the new Spring Boot project using Spring initializer on creating the project including the below dependencies into the project.
Dependencies
- Spring Web
- Spring DevTools
- Lombok
Once create the project then the file structure looks like the below image.

Step 2: Resource Image
We will save the sample image at the location of the below path.
Go to src > java > resources > static > images > image.png and save the sample image.

Step 3: Create the Image Controller class
Go to src > org.example.springimagedemo > controller > ImageController and put the below code.
Java
package org.example.springimagedemo.controller;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
import java.nio.file.Files;
@Controller
public class ImageController {
@GetMapping("/image")
public ResponseEntity<byte[]> getImage() throws IOException {
// Load image data
ClassPathResource resource = new ClassPathResource("static/images/image.png");
byte[] imageData = Files.readAllBytes(resource.getFile().toPath());
// Set content type header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
// Return image data as ResponseEntity
return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
}
}
Step 4: Main Class
No need to change the main class of the application.
Java
package org.example.springimagedemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringImageDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringImageDemoApplication.class, args);
}
}
Step 5: Run the Application
Once we run the application, then the project will run at port 8080.

Output:
Endpoint: http://localhost:8080/image
When we open above URL in browser, we will see the below image as result.

This example project demonstrates how to serve the image named image.png located in the resource path. When a GET request is made to /image, the controller loads the image data and returns it as the response with the appropriate content-type header.
Similar Reads
Returning an Image or a File with Spring 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 endpoint
3 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
Data Binding in Spring MVC with Example Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a var
8 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
What is Spring Data REST? Spring Data REST is a framework that exposes Spring Data repositories as RESTful endpoints. It allows you to create REST APIs for your data without having to write any controller code. Under the hood, Spring Data REST uses Spring Data repositories to access and manage data. So you first need to defi
7 min read
Data Transfer Object (DTO) in Spring MVC with Example In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you're working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for
7 min read