Open In App

How to Send Images in Spring Boot without using Servlet and Redundant JSP Codes?

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Open IntelliJ IDE and in the Controller section of your project inside the Controller class you need to build the Image serve method. The Image serve method looks like below and as you have to collect the Image response use @GetMapping Annotation to collect the image.

ImageHandler Controller Method

ImageHandler Controller Method

Create a directory to upload images from the system to your respective IDE; here in our case, It is IntelliJ.

Creating Directory In IDE to upload Image

Creating Directory In IDE to upload Image

Here, we created a directory as Mica Check and uploaded the file below:

Directory along with uploaded File

Directory along with uploaded File

Now time to get the Image from FileInput Stream and put it under the try-catch block as below 

Adding an Image from InputStream and giving the path of the file

Adding an Image from InputStream and giving the path of the file 

You getting an Image response and for that, you need to reflect the content type of the Image by adding HTTPSERVLET RESPONSE in the controller method parameter and the content type should be MEDIATYPE.(FILE_FORMAT)

Java




@GetMapping("/serve-image")
public void serveImageHandler(HttpServletResponse response) {
  
        try {
            InputStream fileInputStream= new FileInputStream("MicaCheck/Resignation__Approval.png");
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            StreamUtils.copy(fileInputStream,response.getOutputStream());
        } catch(Exception e) {
            e.printStackTrace();
        }
  
}


StreamUtils.copy(file input stream,response.getOutputStream());

The above lines copy the file input stream to the response.getOutputStream. Now your Image Serve Controller method is ready. Now test it on the postman client by hitting URI as in the below Image.

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads