ShoutLoudz
Published in

ShoutLoudz

Spring Boot: Upload and Download Images using JPA

Photo by Petrebels on Unsplash

In this post we are going discuss about How to upload an Image into Database, and then download it back. We will be using Spring Boot, Postgres and Postman for testing out APIs.

So this post will be useful If you are implementing any real-world application where you need to store the images and then send them back to the user when requested.

There are multiple ways to store images-

1. Store Images in Database.

2. Store images in File System

The above types we can select based on our need, Suppose if we want more secure access and less frequently used images then we should go with DB, otherwise, the File system is preferred if we want faster access like for web applications where the image is used frequently.

Getting an image from DB involves a lot of steps so it creates delay while getting from a server file system is straightforward.

Read more about File System vs DB for more understanding.

In this post, I will be using Postgres Database for storing images.

Overview

API Specification:

  1. /image POST = For saving image into Database.
  2. /image/info/{name} GET = For getting info of stored image
  3. /image/{name} GET = Get the stored image.

Development Process:

  1. Create a project from https://start.spring.io/ with web and JPA dependency.
  2. Configure Database driver and properties.
  3. Create Packages like — entity, repo, service, controller, util

Now we will start our ImageData class which is used for storing image properties into DB.

Next will be our repo, there we will have one method for fetching images from DB by Name.

public interface ImageDataRepository extends JpaRepository<ImageData, Long> {
Optional<ImageData> findByName(String name);
}

Now we will just create one service class for business logic related to storing and retrieving image data.

Then from controller class we will define our endpoints and will call the service class methods.

Now after this we will start testing our application using Postman.

So In postman for uploading a file in POST call -> Select form-data and then from dropdown -> select file -> upload from your system.

We can use compression and decompression while storing and getting images.

Now our example is ready, next we can use this concept in different applications.

Thanks for reading!!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chakresh Tiwari

Chakresh Tiwari

464 Followers

Software Engineer at Cisco , Sharing my knowledge and experience related to work. I am here to help learners to prepare for tech interviews