4. How to insert image in database using Spring MVC

How to insert image in database using Spring MVC

https://www.websparrow.org/spring/how-to-insert-image-in-database-using-spring-mvc


================================================================================================================
TABLES
================================================================================================================

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


================================================================================================================
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>


================================================================================================================
CONFIG
================================================================================================================
-----------------------------------------------------------------------------------------------------------------
FontControllerConfig 
-----------------------------------------------------------------------------------------------------------------
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[] { "/" };
}
}

-----------------------------------------------------------------------------------------------------------------
WebMvcConfig 
-----------------------------------------------------------------------------------------------------------------

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
================================================================================================================

-----------------------------------------------------------------------------------------------------------------
ImageDao 
-----------------------------------------------------------------------------------------------------------------

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
================================================================================================================
-----------------------------------------------------------------------------------------------------------------
ImageController 
-----------------------------------------------------------------------------------------------------------------

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
================================================================================================================
-----------------------------------------------------------------------------------------------------------------
index.jsp
-----------------------------------------------------------------------------------------------------------------

<%@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>

-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment