In this example, I am explaining how to upload image or file into the database(here I am using the MySQL database).
System requirements:
First, create the table in your respective database.
Then, create the HTML file with input fields like first name last name and photo.
Here is my sample HTML file.
Next, create the servlet class to get the data from the input page and also get the data from the database. In servlet to the text filed data value, we can use request. getparameter method To get the photo use the get part method and create input stream instance and use file part.getInputStream() method to get the whole image data.
DB connection steps
Here is my success.html
System requirements:
- Java installed in your system (if it's not installed, download from here: "https://www.java.com/en/download/")
- Mysql installed in your system(if it's not installed, download from here: "https://www.mysql.com/downloads/")
- Netbeans or Eclipse ide for faster web development.
First, create the table in your respective database.
create table javasnippets.fileinfo1(fistname varchar(100),lastname varchar(100),photo blob)
Then, create the HTML file with input fields like first name last name and photo.
Here is my sample HTML file.
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>File Upload to Database Demo</title> <meta charset="UTF-8"> <meta name="description" content="Free Web tutorials"> <meta name="keywords" content="HTML,CSS,XML,JavaScript"> <meta name="author" content="John Doe"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <center> <h1>File Upload to Database Demo</h1> <form method="post" action="uploadServlet" enctype="multipart/form-data"> <table border="1" align="center" rules="all"> <tr> <td>First Name: </td> <td><input type="text" name="firstName" /></td> </tr> <tr> <td>Last Name: </td> <td><input type="text" name="lastName" /></td> </tr> <tr> <td>Portrait Photo: </td> <td><input type="file" name="photo" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Save"> </td> </tr> </table> </form> </center> </body> </html>
Next, create the servlet class to get the data from the input page and also get the data from the database. In servlet to the text filed data value, we can use request. getparameter method To get the photo use the get part method and create input stream instance and use file part.getInputStream() method to get the whole image data.
DB connection steps
- Load the driver class
- Create the connection object.
- Create the statement object using the connection object.
- Execute the statement.
- close the connection object.
- close the input stream object.
- After executing the statement it will return the integer value, if the file is upload successfully it will return the 1 then we can print the success message in an HTML page using the response.sendRedirect method.
Here is my servlet class
package com.file; /** * * @author Javasnippets */ import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; 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; @WebServlet("/uploadServlet") @MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB public class FileUploadDBServlet extends HttpServlet { // database connection settings private String dbURL = "jdbc:mysql://localhost:3306/javasnippets"; private String dbUser = "root"; private String dbPass = ""; 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; // input stream of the upload file // obtains the upload file part in this multipart request Part filePart = request.getPart("photo"); if (filePart != null) { // prints out some information for debugging // obtains input stream of the upload file inputStream = filePart.getInputStream(); } try { // connects to the database Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(dbURL, dbUser, dbPass); System.out.println("connected"); // constructs SQL statement String sql = "INSERT INTO javasnippets.fileinfo(first_name, last_name, photo) values (?, ?, ?)"; System.out.println(sql); 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) { System.out.println("File uploaded and saved into database"); response.sendRedirect("success.html"); } } catch (Exception e) { inputStream.close(); System.out.println(e); } } }
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>success</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div> <h3 align="center">File uploaded Successfully into database</h3> </div> </body> </html>