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 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.