Spring Boot Upload Image Example (2024)
In this tutorial, we'll show you how to upload image in Spring Boot application with following rest endpoints.
POST
method to Upload image usingMultipartFile[] file
as a parameter.GET/image/info
method with image name, provide image information.GET/image
method with image name, can view image.
Create Spring Boot Project from Spring Initializer site https://start.spring.io/
Project Structure
Maven Dependency
All we need is spring-boot-starter-web
for RestController,
mysql-connector-java
for database dependencies in pom.xml, add
org.projectlombok
for auto generating getters/setters/constructor.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-upload-image</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-upload-image</name>
<description>Spring Boot Upload Image</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Database Connection Details
Provide database details in application.properties
.
spring.datasource.url=jdbc:mysql://localhost/imagesdb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
RestController to upload image
Create RestController class and define below rest endpoint:
POST
method to Upload image usingMultipartFile[] file
as a parameter.GET/image/info
method with image name, provide image information.GET/image
method with image name, can view image.
package com.techgeeknext.controller;
import com.techgeeknext.entities.Image;
import com.techgeeknext.repositories.ImageRepository;
import com.techgeeknext.util.ImageUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Optional;
@RestController
//@CrossOrigin(origins = "http://localhost:8082") open for specific port
@CrossOrigin() // open for all ports
public class ImageController {
@Autowired
ImageRepository imageRepository;
@PostMapping("/upload/image")
public ResponseEntity<ImageUploadResponse> uplaodImage(@RequestParam("image") MultipartFile file)
throws IOException {
imageRepository.save(Image.builder()
.name(file.getOriginalFilename())
.type(file.getContentType())
.image(ImageUtility.compressImage(file.getBytes())).build());
return ResponseEntity.status(HttpStatus.OK)
.body(new ImageUploadResponse("Image uploaded successfully: " +
file.getOriginalFilename()));
}
@GetMapping(path = {"/get/image/info/{name}"})
public Image getImageDetails(@PathVariable("name") String name) throws IOException {
final Optional<Image> dbImage = imageRepository.findByName(name);
return Image.builder()
.name(dbImage.get().getName())
.type(dbImage.get().getType())
.image(ImageUtility.decompressImage(dbImage.get().getImage())).build();
}
@GetMapping(path = {"/get/image/{name}"})
public ResponseEntity<byte[]> getImage(@PathVariable("name") String name) throws IOException {
final Optional<Image> dbImage = imageRepository.findByName(name);
return ResponseEntity
.ok()
.contentType(MediaType.valueOf(dbImage.get().getType()))
.body(ImageUtility.decompressImage(dbImage.get().getImage()));
}
}
Image Entity
Create the Image entity class to store the image data in database.
package com.techgeeknext.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Table(name = "image")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Image {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "type")
private String type;
@Column(name = "image", unique = false, nullable = false, length = 100000)
private byte[] image;
}
Test Upload Image Example
POST - Upload Image
Open POSTMAN and select the value to upload the image by using http://localhost:8080/upload/image request.GET - INFO of uploaded image
Open POSTMAN and get the info of uploaded image by using http://localhost:8080/get/image/info/techgeeknext.PNG request.GET - VIEW uploaded image
Open POSTMAN and View uploaded image by using http://localhost:8080/get/image/techgeeknext.PNG request.
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Upload Image Example