File Uploading Using Spring Boot Example

Hey Learners, In this post we will learn File Uploading using Spring boot full tutorials with video. This tutorials will be helpful for you Images uploading using spring boot, MVC, Data Jpa , & Thymeleaf.

Guys first watch this video after used this code you will be easily understand. In this tutorials i used backend spring boot ,Spring MVC, Data JPA and frontend Thymleaf technologies, Html, CSS & Bootstrap.

Image Uploading Using Spring boot video

File Uploading Using Spring boot Project Structure

Images Uploading Source code

ImageUploadingApplication.java

package com.becoder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ImageUploadingApplication {

	public static void main(String[] args) {
		SpringApplication.run(ImageUploadingApplication.class, args);
	}

}

HomeController.java

package com.becoder.controller;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.becoder.model.Images;
import com.becoder.repository.uploadRepository;

@Controller
public class HomeController {

	@Autowired
	private uploadRepository uploadRepo;

	@GetMapping("/")
	public String index(Model m) {

		List<Images> list = uploadRepo.findAll();

		m.addAttribute("list", list);
		
		return "index";
	}

	@PostMapping("/imageUpload")
	public String imageUpload(@RequestParam MultipartFile img, HttpSession session) {

		Images im = new Images();
		im.setImageName(img.getOriginalFilename());

		Images uploadImg = uploadRepo.save(im);

		if (uploadImg != null) {
			try {

				File saveFile = new ClassPathResource("static/img").getFile();

				Path path = Paths.get(saveFile.getAbsolutePath() + File.separator + img.getOriginalFilename());
				//System.out.println(path);
				Files.copy(img.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		session.setAttribute("msg", "Image Upload Sucessfully");

		return "redirect:/";
	}

}

Images.java

package com.becoder.model;

import javax.persistence.Entity;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Images {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;

	private String imageName;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getImageName() {
		return imageName;
	}

	public void setImageName(String imageName) {
		this.imageName = imageName;
	}

}

uploadRepository.java

package com.becoder.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.becoder.model.Images;

public interface uploadRepository extends JpaRepository<Images, Integer> {

}

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
	crossorigin="anonymous">
</head>
<body class="bg-light">

	<nav class="navbar navbar-expand-lg navbar-dark bg-success">
		<div class="container-fluid">
			<a class="navbar-brand" href="#">Image Uploading Site</a>
			<button class="navbar-toggler" type="button"
				data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
				aria-controls="navbarSupportedContent" aria-expanded="false"
				aria-label="Toggle navigation">
				<span class="navbar-toggler-icon"></span>
			</button>
			<div class="collapse navbar-collapse" id="navbarSupportedContent">
			</div>
		</div>
	</nav>


	<div class="container">

		<th:block th:if="${session.msg}">
			<p class="text-center fs-4 text-success">[[${session.msg}]]</p>
			<th:block th:text="${#session.removeAttribute('msg')}"></th:block>
		</th:block>

		<div class="row">
			<div class="col-md-6 offset-md-3 mt-4">

				<form action="imageUpload" enctype="multipart/form-data"
					method="post">
					<div class="mb-3">
						<input type="file" name="img" class="form-control">
					</div>

					<div class="text-center">
						<button class="btn btn-primary">Upload</button>
					</div>
				</form>

			</div>

		</div>
	</div>
	<hr>

	<div class="container">
		<div class="row">

			<div class="col-md-3" th:each="im:${list}">
				<div class="card">
					<div class="card-body">
						<img alt="" th:src="@{'img/'+${im.imageName}}" width="100%"
							height="300px">
					</div>
				</div>
			</div>


		</div>
	</div>


</body>
</html>

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/image_upload
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.becoder</groupId>
	<artifactId>Image-Uploading</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Image-Uploading</name>
	<description>Image-Uploading Tutorials</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Conclusion

Guys In this Post we learnt File uploading using spring boot , image uploading using spring boot example.

Leave a Comment