How to upload a file in spring boot using the form
November 2, 2018 | Spring boot complete tutorial with example | 2 Comments
In this example we will learn about multipart file upload spring boot using HTML form, For multipart file upload in spring boot, we will follow the given steps:
- Create an Entity Class and use @Lob annotation on a column for the image.
- Make a controller that provides endpoint URL to upload and retrieve a file.
- Make a service class for Bussiness logic.
- Make a DAO interface that extends CrudRepository for performing database operations.
Project Structure
Project Dependency
Add the Following Dependency in your pom.xml file
<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-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
application.properties
add the following in your application.properties file
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp # database connection spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/image spring.datasource.username=root spring.datasource.password=12345@ spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE # for logging logging.level.org.springframework.web=ERROR logging.level.com.vasu=DEBUG # Logging pattern for the console logging.pattern.console= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} %L- %msg%n" # Logging pattern for file logging.pattern.file=="%d{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%M %L - %msg%n" # use For Exact Naming Of Column and Table in Hibernate otherwise hibernate add _ in camelcase names spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl #use for define max file size to upload spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB
- Create an Entity Class and paste the given lines there.
MyModel.java
package com.vasu.SpringBootFileUpload.Model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; /** * * @author Vasu Rajput */ @Entity @Table(name = "ImageProfile") public class MyModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "Id") private long id; @Column(name = "Name") private String name; @Lob @Column(name = "Image") private byte[] image; public MyModel() { super(); // TODO Auto-generated constructor stub } public MyModel(String name, byte[] image) { super(); this.name = name; this.image = image; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } }
2 Make a Controller class for the endpoint.
MyController.class
package com.vasu.SpringBootFileUpload.controller; import com.vasu.SpringBootFileUpload.Model.MyModel; import com.vasu.SpringBootFileUpload.Service.MyService; import java.util.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; /** * * @author Vasu Rajput */ @Controller public class MyController { private static final Logger logger = LoggerFactory.getLogger("MyController.class"); @Autowired private MyService myService; @GetMapping("/") public String test() { return "index"; } @PostMapping("/fileupload") public String fileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { try { logger.info("Name= " + name); byte[] image = file.getBytes(); MyModel model = new MyModel(name, image); int saveImage = myService.saveImage(model); if (saveImage == 1) { return "success"; } else { return "error"; } } catch (Exception e) { logger.error("ERROR", e); return "error"; } } @GetMapping("/getDetail/{id}") public String getDbDetils(@PathVariable String id, Model model) { try { logger.info("Id= " + id); MyModel imagesObj = myService.getImages(Long.parseLong(id)); model.addAttribute("id", imagesObj.getId()); model.addAttribute("name", imagesObj.getName()); byte[] encode = java.util.Base64.getEncoder().encode(imagesObj.getImage()); model.addAttribute("image", new String(encode, "UTF-8")); return "imagedetails"; } catch (Exception e) { logger.error("Error", e); model.addAttribute("message", "Error in getting image"); return "redirect:/"; } } }
3 Make a service class for Bussiness logic.
MyService.class
package com.vasu.SpringBootFileUpload.Service; import com.vasu.SpringBootFileUpload.Dao.MyDao; import com.vasu.SpringBootFileUpload.Model.MyModel; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.support.DaoSupport; import org.springframework.stereotype.Service; /** * * @author Vasu Rajput */ @Service public class MyService { private static final Logger logger = LoggerFactory.getLogger("MyService.class"); @Autowired private MyDao dao; public int saveImage(MyModel model) { try { dao.save(model); return 1; } catch (Exception e) { logger.error("ERROR", e); return 0; } } public MyModel getImages(Long id) { Optional findById = dao.findById(id); if (findById.isPresent()) { MyModel getImageDetails = findById.get(); logger.info("id= " + getImageDetails.getId() + " name= " + getImageDetails.getName()); return getImageDetails; } else { return null; } } }
4 Make a DAO interface that extends CrudRepository for performing database operations.
MyDao.java
package com.vasu.SpringBootFileUpload.Dao; import com.vasu.SpringBootFileUpload.Model.MyModel; import org.springframework.data.repository.CrudRepository; /** * * @author Vasu Rajput */ public interface MyDao extends CrudRepository<MyModel, Long> { }
5 Here we have to handle the maximum file size exceed exception, This exception occurs if we upload a file of large size. To handle this we create a class and use @ControllerAdvice and @ExceptionHandler annotation to handle that.
MaxSizeErrorHandler.java
package com.vasu.SpringBootFileUpload.Error; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * * @author Vasu Rajput */ @ControllerAdvice public class MaxSizeErrorHandler { private static final Logger logger = LoggerFactory.getLogger("MaxSizeErrorHandler.class"); @ExceptionHandler public String maxSizeError(MultipartException e, RedirectAttributes redirectAttributes) { logger.info("Max File Size Exception Occurs"); redirectAttributes.addFlashAttribute("message", "Excced Max File Size Error"); return "redirect:/"; } }
Now we create JSP file to create the view for file upload and retrieve images
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>File Upload Example </h1> <br> <hr> <h4 style="color: red;">${message}</h4> <form action="/fileupload" method="POST" enctype="multipart/form-data"> <table> <tr> <td> <input type="text" name="name" required> </td> </tr> <tr> <td> <input type="file" name="file" required> </td> </tr> <tr> <td> <input type="submit"> </td> </tr> </table> </form> </body> </html>
imagedetails.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Details are given below:</h1><hr> <table> <tr> <td>Id</td> <td>${id}</td> </tr> <tr> <td>Name</td> <td>${name}</td> </tr> <tr> <td>Image</td> <td><img src="data:image/jpg;base64,${image} alt="Girl in a jacket" style="width:50px;height:50px;"></img></td> </tr> </table> </body> </html>
success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Successfully uploaded</h1> </body> </html>
error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Error in upload ${message}</h1> </body> </html>
You may also like
Actuator in spring boot for monitoring application
Profiles in Spring boot application
How to deploy spring boot application on docker
2 Comments
Mei Rands
Very good information. Lucky me I discovered your website by accident (stumbleupon). I have saved as a favorite for later!
WWW.XMC.PL
That is really fascinating, You are a very skilled blogger. I have joined your rss feed and stay up for in search of more of your magnificent post. Additionally, Ive shared your web site in my social networks!