In this example we are going to create a project which will enable users to upload the image into the database.
First of all turn on mysql database connection and open the mysql command line and paste the following sql script and create the new database as well as table.
Now, lets create a dynamic web project into the eclipse and design the structure as follows:
Now, let's create the front end using the jsp pages.
uploadImage.jsp
submit.jsp
db.properties
DbUtil.java
UploadServlet.java
Now, we are ready to run the project and once we run the project we are able to view the following result.
Click here to download the code.
You may also like...
First of all turn on mysql database connection and open the mysql command line and paste the following sql script and create the new database as well as table.
create database AppDB; use AppDB; CREATE TABLE `contacts` ( `contact_id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(45) DEFAULT NULL, `last_name` varchar(45) DEFAULT NULL, `photo` mediumblob, PRIMARY KEY (`contact_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
Now, lets create a dynamic web project into the eclipse and design the structure as follows:
Now, let's create the front end using the jsp pages.
uploadImage.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>File Upload</title> </head> <body> <h1>Upload any image to mysql DB</h1> <form method="post" action="fileUpload" enctype="multipart/form-data"> <table> <tr> <td>First Name:</td> <td><input type="text" name="firstName" size="10" required="required" /></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" name="lastName" size="10" required="required" /></td> </tr> <tr> <td>Choose Image:</td> <td><input type="file" name="photo" size="10" required="required" /></td> </tr> <tr> <td><input type="submit" value="Submit"></td> <td><input type="reset" value="Clear" /></td> </tr> </table> </form> </body> </html>
submit.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Success</title> </head> <body> <h3><%=request.getAttribute("Message")%></h3> </body> </html>
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/AppDB user=root password=password
DbUtil.java
package com.amzi.util; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DbUtil { private static Connection connection = null; public static Connection getConnection() { if (connection != null) return connection; else { try { Properties prop = new Properties(); InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties"); prop.load(inputStream); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); Class.forName(driver); connection = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return connection; } } }
UploadServlet.java
package com.amzi.servlet; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.amzi.util.DbUtil; @WebServlet("/fileUpload") @MultipartConfig(maxFileSize = 16177215) // upload file up to 16MB public class UploadServlet extends HttpServlet { private static final long serialVersionUID = -1623656324694499109L; private Connection conn; public UploadServlet() { conn = DbUtil.getConnection(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // gets values of text fields String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); InputStream inputStream = null; // obtains the upload file part in this multipart request Part filePart = request.getPart("photo"); if (filePart != null) { // debug messages System.out.println(filePart.getName()); System.out.println(filePart.getSize()); System.out.println(filePart.getContentType()); // obtains input stream of the upload file inputStream = filePart.getInputStream(); } String message = null; // message will be sent back to client try { // constructs SQL statement String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, firstName); statement.setString(2, lastName); if (inputStream != null) { // fetches input stream of the upload file for the blob column statement.setBlob(3, inputStream); } // sends the statement to the database server int row = statement.executeUpdate(); if (row > 0) { message = "Image is uploaded successfully into the Database"; } } catch (SQLException ex) { message = "ERROR: " + ex.getMessage(); ex.printStackTrace(); } // sets the message in request scope request.setAttribute("Message", message); // forwards to the message page getServletContext().getRequestDispatcher("/submit.jsp").forward( request, response); } }
Now, we are ready to run the project and once we run the project we are able to view the following result.
Click here to download the code.
You may also like...