Javascript required
Skip to content Skip to sidebar Skip to footer

Java Servlet/jsp Image Upload Along With Form Values

This tutorial shows how to implement a Java web application (using Servlet and JSP) that uploads files to server and save the files into database.

Table of content:

    1. Creating MySQL database table
    2. Coding upload form page
    3. Coding file upload servlet
    4. Coding message page
    5. Testing the application and verifying file stored in database

The application applies the post-obit technologies:

    • Servlet 3.0+: Since Servlet 3.0 we can write code to handle file upload hands. For details, read this tutorial: Java file upload with servlet. The code is working with latest version of Servlet API (Servlet 4.0 or iv.1)
    • MySQL database 5.v or later: We will store uploaded files in MySQL database. For more than details about how to store files in MySQL database, read this article.

The application will consist of the following source files:

    • Upload.jsp: presents a course which allows users entering some information (first proper noun and terminal name), and picking up a file (a portrait image).
    • FileUploadDBServlet: captures input from the upload form, saves the upload file into database, and forwards the users to a bulletin page.
    • Bulletin.jsp: shows either successful or error message.

At present, permit's go through each part of the awarding in details.

i. Creating MySQL database table

First, let's create a database and a table in MySQL. Execute the following script using either MySQL Control Line Customer or MySQL Workbench:

create database AppDB;  use AppDB;  CREATE Tabular array `contacts` (   `contact_id` int(11) NOT NULL AUTO_INCREMENT,   `first_name` varchar(45) DEFAULT NULL,   `last_name` varchar(45) DEFAULT NULL,   `photograph` mediumblob,   Primary Key (`contact_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

 The script will create a database named AppDB and a table named contacts. File will be stored in the column photograph which is of blazon mediumblob which can store up to 16 MB of binary data. For larger files, use longblob (up to iv GB).

ii. Coding upload grade page

Write code for the upload form every bit follows (Upload.jsp):

<%@ page linguistic communication="java" contentType="text/html; charset=ISO-8859-one" 	pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  	"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <championship>File Upload to Database Demo</championship> </head> <body> 	<middle> 		<h1>File Upload to Database Demo</h1> 		<class method="post" action="uploadServlet" enctype="multipart/form-data"> 			<table border="0"> 				<tr> 					<td>Kickoff Name: </td> 					<td><input type="text" proper noun="firstName" size="fifty"/></td> 				</tr> 				<tr> 					<td>Last Name: </td> 					<td><input blazon="text" name="lastName" size="50"/></td> 				</tr> 				<tr> 					<td>Portrait Photograph: </td> 					<td><input type="file" proper name="photograph" size="50"/></td> 				</tr> 				<tr> 					<td colspan="ii"> 						<input type="submit" value="Save"> 					</td> 				</tr> 			</tabular array> 		</form> 	</center> </body> </html>

 This page shows two text fields (starting time proper noun and last name) and a file field which allows the users choosing a file to upload. The action aspect of this form is set to uploadServlet which is URL mapping of the servlet we will create in the next section.

3. Coding file upload servlet

Create a servlet class named FileUploadDBServlet.java with the following code:

package net.codejava.upload;  import java.io.IOException; import java.io.InputStream; import java.sql.Connectedness; import java.sql.DriverManager; 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;  @WebServlet("/uploadServlet") @MultipartConfig(maxFileSize = 16177215)	// upload file's size upwardly to 16MB public class FileUploadDBServlet extends HttpServlet { 	 	// database connection settings 	private String dbURL = "jdbc:mysql://localhost:3306/AppDB"; 	individual String dbUser = "root"; 	private String dbPass = "secret"; 	 	protected void doPost(HttpServletRequest asking, 			HttpServletResponse response) throws ServletException, IOException { 		// gets values of text fields 		String firstName = request.getParameter("firstName"); 		Cord lastName = request.getParameter("lastName"); 		 		InputStream inputStream = nada;	// input stream of the upload file 		 		// obtains the upload file part in this multipart request 		Part filePart = asking.getPart("photo"); 		if (filePart != zilch) { 			// prints out some information for debugging 			System.out.println(filePart.getName()); 			System.out.println(filePart.getSize()); 			Organisation.out.println(filePart.getContentType()); 			 			// obtains input stream of the upload file 			inputStream = filePart.getInputStream(); 		} 		 		Connectedness conn = null;	// connection to the database 		String message = null;	// bulletin will be sent back to client 		 		try { 			// connects to the database 			DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 			conn = DriverManager.getConnection(dbURL, dbUser, dbPass);  			// constructs SQL statement 			String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)"; 			PreparedStatement statement = conn.prepareStatement(sql); 			argument.setString(1, firstName); 			statement.setString(ii, lastName); 			 			if (inputStream != zip) { 				// fetches input stream of the upload file for the blob cavalcade 				statement.setBlob(3, inputStream); 			}  			// sends the statement to the database server 			int row = statement.executeUpdate(); 			if (row > 0) { 				message = "File uploaded and saved into database"; 			} 		} catch (SQLException ex) { 			message = "ERROR: " + ex.getMessage(); 			ex.printStackTrace(); 		} finally { 			if (conn != naught) { 				// closes the database connection 				try { 					conn.shut(); 				} catch (SQLException ex) { 					ex.printStackTrace(); 				} 			} 			// sets the message in request telescopic 			request.setAttribute("Message", bulletin); 			 			// forrard to the message page 			getServletContext().getRequestDispatcher("/Message.jsp").forward(asking, response); 		} 	} }

In this servlet, we use two annotations:

    • @WebServlet: marks this servlet so that the servlet container will load it at startup, and map it to the URL blueprint /uploadServlet.
    • @MultipartConfig: indicates this servlet will handle multipart asking. We restrict maximum size of the upload file up to sixteen MB.

The doPost() method carries out all the details. Here, there are three noticeable points:

  • Obtaining the function of upload file in the request:
    Role filePart = request.getPart("photo");            
    The name "photo" is name of the file input field in the Upload.jsp page.
  • Obtaining input stream of the upload file:
    inputStream = filePart.getInputStream();            
  • And pass the input stream into the prepared statement:
argument.setBlob(3, inputStream);

If you want to master Java Servlet and JSP programming, I recommend you to read this fantabulous Head First Servlet and JSP volume.

4. Coding message page

Create a JSP page named as Message.jsp with the following code:

<%@ page linguistic communication="coffee" contentType="text/html; charset=ISO-8859-i"     pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  	"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Blazon" content="text/html; charset=ISO-8859-1"> <title>Message</title> </caput> <torso> 	<centre> 		<h3><%=request.getAttribute("Message")%></h3> 	</eye> </trunk> </html>

This folio simply displays value of the variable "Message" in the request telescopic.

5. Testing the application and verifying file stored in database

Supposing the application is deployed on localhost at port 8080, under the context root /FileUploadDatabase, blazon the following URL:

http://localhost:8080/FileUploadDatabase/Upload.jsp

The post-obit upload form is displayed:

file upload form

Blazon start proper name, terminal name, and pick up an paradigm file. Click Save push button, if everything is going well, this message appears:

upload succeed message

To verify that the file is stored successfully in the database, open a new SQL Editor in MySQL Workbench and execute the following query:

select * from contacts;

The query would return the newly inserted record, right click on the Hulk cell of the column photo, and select Open up Value in Editor from the context carte:

MySQL open value in editor

A dialog appears and we can meet the image in the Image tab:

view blob data in MySQL

If you want to retrieve the file stored in database programmatically, read the tutorial: How to recall file data from database.

Notation : By default, MySQL restricts the size of data packet can be sent in a query to only 1 MB. And then yous may become an error if trying to upload a file bigger than this limit. To increase this size limit, gear up the max_allowed_packet variable in MySQL, as discussed in this tutorial.

To larn a consummate e-commerce website development with Java, I recommend you lot to take this Build an e-commerce website with Java course.

Related Tutorials:

  • How to upload files with Java Servlet
  • How to store files in database with JDBC
  • Coffee Servlet, JSP and JDBC CRUD Tutorial

Other Java Coding Tutorials:

  • 10 Common Mistakes Every Beginner Coffee Programmer Makes
  • 10 Java Core Best Practices Every Java Developer Should Know
  • How to go a expert developer? 13 tasks you should practice now
  • How to calculate MD5 and SHA hash values in Coffee
  • How to generate random numbers in Java
  • Java File Encryption and Decryption Example

Nigh the Writer:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Coffee 1.four and has been falling in love with Java since then. Brand friend with him on Facebook and watch his Java videos yous YouTube.

Add comment

currhougmenseed.blogspot.com

Source: https://www.codejava.net/coding/upload-files-to-database-servlet-jsp-mysql