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 APICommonsMultipartResolver 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.

	<!-- spring mvc dependency -->
	<!-- spring jdbc dependency -->
	<!-- mysql databse connector -->
	<!-- apache commons file upload api -->

Project Structure

Final project structure of our application in Eclipse IDE will look like as follows.

How to insert image in database using Spring MVC

Database Schema

Find the structure of table used in this application.

CREATE TABLE `student` (
  `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;


public class FontControllerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

	protected Class<?>[] getRootConfigClasses() {

		return new Class[] { WebMvcConfig.class };

	protected Class<?>[] getServletConfigClasses() {

		return null;

	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;

@ComponentScan(basePackages = { "org.websparrow.controller", "org.websparrow.dao" })
public class WebMvcConfig {

	public InternalResourceViewResolver viewResolver() {

		InternalResourceViewResolver vr = new InternalResourceViewResolver();

		return vr;

	public MultipartResolver multipartResolver() {
		return new CommonsMultipartResolver();

	public DriverManagerDataSource getDataSource() {

		DriverManagerDataSource ds = new DriverManagerDataSource();

		return ds;

	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 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();


		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;

public class ImageController {

	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());


JSP pages for user interaction.

<%@page isELIgnored="false"%>
<h2>How to insert image in database using Spring MVC</h2>

<form action="InsertImage" method="post" enctype="multipart/form-data">

	Name: <input type="text" name="name">
	Age: <input type="number" name="age">
	Photo: <input type="file" name="photo">
	<input type="submit" value="Submit">






Now everything set, start your Tomcat server and deploy the project. You will get the following result.

How to insert image in database using Spring MVC

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.

How to insert image in database using Spring MVC


  1. How to upload Image in database using Struts 2
  2. Interface MultipartFile
  3. Interface MultipartResolver
  4. Class CommonsMultipartResolver
  5. Apache Commons FileUpload

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.