How to insert image in database using Spring MVC
This page will walk through How to insert an image in database using Spring MVC. Spring framework uses the MultipartResolver
interface to handle the file upload by integrating Apache Commons FileUpload API. CommonsMultipartResolver
is the implementation class of MultipartResolver
interface.
To upload file on the server or insert images into the database, you must add enctype="multipart/form-data"
attribute in the form tag, so that Spring web application knows that the request contains file data that needs to be processed and make sure enctype attribute can be used only with method=”post”. I have already written a similar article in Struts 2 to upload an image into the database.
Steps to follow
To upload file on the server or insert images into the database in Spring MVC application, these following steps need to be followed.
Step 1: Add the enctype="multipart/form-data"
attribute in the form tag.
Step 2: Register a MultipartResolver
bean, and returns CommonsMultipartResolver
in the configuration file/class and make sure bean name must be “multipartResolver”, by default Spring uses method name as bean name.
Step 3: Create the database connection object and inject it to the DAO class.
Step 4: Use the injected database connection to query with the database using JdbcTemplate
.
Step 5: And finally create a controller class that handles the user request.
Tools Used
Find the list of tools/technologies used in this application.
Eclipse Oxygen | Tomcat 9 | JDK 8 | Maven 3 | Spring5.0.2.RELEASE | MySQL Database
Dependencies Required
These are the required dependencies that must be your build path. To get all these dependencies all the following code in your pom.xml.
<dependencies>
<!-- spring mvc dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- spring jdbc dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- mysql databse connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- apache commons file upload api -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
Project Structure
Final project structure of our application in Eclipse IDE will look like as follows.
Database Schema
Find the structure of table used in this application.
CREATE TABLE `student` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`photo` mediumblob,
PRIMARY KEY (`id`)
);
Front Controller & MVC Configuration
I have used annotation based configuration, so the front controller class will be:
package org.websparrow.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class FontControllerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
And the Spring MVC configuration class will be given below. In this class, we will create a database connection, register the MultipartResolver
and InternalResourceViewResolver, etc.
package org.websparrow.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.websparrow.dao.ImageDao;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "org.websparrow.controller", "org.websparrow.dao" })
public class WebMvcConfig {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/");
vr.setSuffix(".jsp");
return vr;
}
@Bean
public MultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
@Bean
public DriverManagerDataSource getDataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/websparrow");
ds.setUsername("root");
ds.setPassword("");
return ds;
}
@Bean
public ImageDao getConnectionObject() {
return new ImageDao(getDataSource());
}
}
DAO Class
Create a DAO class that query with the database and insert records into the database. Make sure file must be converted into bytes array
before inserting into the database.
package org.websparrow.dao;
import java.io.IOException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.multipart.MultipartFile;
public class ImageDao {
private JdbcTemplate jdbcTemplate;
public ImageDao(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public int inserRecords(String name, Integer age, MultipartFile photo) throws IOException {
byte[] photoBytes = photo.getBytes();
String sql = "INSERT INTO STUDENT(NAME,AGE,PHOTO) VALUES (?,?,?)";
return jdbcTemplate.update(sql, new Object[] { name, age, photoBytes });
}
}
Controller Class
Create a controller class that handles the user request and @Autowired
annotation inject an instance of the ImageDao
implementation into this controller automatically.
package org.websparrow.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.websparrow.dao.ImageDao;
@Controller
public class ImageController {
@Autowired
ImageDao imageDao;
@RequestMapping(value = "/InsertImage", method = RequestMethod.POST)
public ModelAndView save(@RequestParam("name") String name, @RequestParam("age") Integer age,
@RequestParam("photo") MultipartFile photo) {
try {
imageDao.inserRecords(name, age, photo);
return new ModelAndView("index", "msg", "Records succesfully inserted into database.");
} catch (Exception e) {
return new ModelAndView("index", "msg", "Error: " + e.getMessage());
}
}
}
Views
JSP pages for user interaction.
<%@page isELIgnored="false"%>
<html>
<body>
<h2>How to insert image in database using Spring MVC</h2>
<form action="InsertImage" method="post" enctype="multipart/form-data">
<pre>
Name: <input type="text" name="name">
Age: <input type="number" name="age">
Photo: <input type="file" name="photo">
<input type="submit" value="Submit">
</pre>
</form>
<p>${msg}</p>
</body>
</html>
Output
Now everything set, start your Tomcat server and deploy the project. You will get the following result.
If the records successfully inserted, you will get the Records successfully inserted into the database message on the same page. You can also check your database to ensure that.
References
- How to upload Image in database using Struts 2
- Interface MultipartFile
- Interface MultipartResolver
- Class CommonsMultipartResolver
- Apache Commons FileUpload
Download Source Code: how-to-insert-image-in-database-using-spring-mvc.zip