Servlet code for Uploading and Storing PDF file in MySQL database example.

In this tutorial, let us see that how to upload and store a PDF file in a BLOB field in MySql database using servlet. In this example, let us design an application to store e-books in a table in mySql database.

Additional Jars used in this example:


Project Structure:

fileupload structure

Let us see the steps

Step 1: Create a MySql table named book having the following two fields

bookId varchar(10)
bookContent MEDIUMBLOB

DDL for creating the table :

CREATE TABLE Book (BookId varchar (10) not null , BookContent MEDIUMBLOB, Primary key (BookId))

Step 2: Design a html form (fileUpload.jsp) to upload a file. fileUpload jsp contains two input fields bookId and file. The encryption type is set to multipart/form-data. The JSP code is given below.


<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">

        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <form method="POST" action="FileUpload" enctype="multipart/form-data" >
        <tr><td>Book Id</td>
        <td><input type="text" name="bookId" /></td>
        <tr><td>Book Pdf</td>
            <td><input type="file" name="file" id="file" /> </td>
        <td colspan="2">
            <input type="submit" value="Upload" name="upload" id="upload" /> </td>

Step 3: Write servlet code to accept the PDF file and storing the content as binary stream in blob field. The below servlet is annotated with MultipartConfig which comes with servlet 3.0. MultipartConfig annotation indicates that the servlet receives the request of type multipart/form-data. getPart is used to retrieve the file contents, content type, size, etc.. The servlet code also includes the simple validation to check whether the file is valid pdf and the size of the file is with in the limit. Code is given below.

package net.javaonline.servlet.fileupload;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

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;

public class FileUploadPdf extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,  HttpServletResponse response)       throws ServletException, IOException {

	    final Part filePart = request.getPart("file");
	    String bookId = request.getParameter("bookId");

	    InputStream pdfFileBytes = null;
	    final PrintWriter writer = response.getWriter();

	    try {

	      if (!filePart.getContentType().equals("application/pdf"))
		    		   writer.println("<br/> Invalid File");

     	   else if (filePart.getSize()>1048576 ) { //2mb
     		  writer.println("<br/> File size too big");

	        pdfFileBytes = filePart.getInputStream();  // to get the body of the request as binary data

	        final byte[] bytes = new byte[pdfFileBytes.available()];
;  //Storing the binary data in bytes array.

	        Connection  con=null;
	         Statement stmt=null;

		       try {
		    	     con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","*******");
		          } catch (Exception e) {

		      try {
		    	  stmt = con.createStatement();
		    	  //to create table with blob field (One time only)
		    	  stmt.executeUpdate("CREATE TABLE Book (BookId varchar (10) not null , BookContent MEDIUMBLOB, Primary key (BookId))");

		      } catch (Exception e) {
		        		System.out.println("Tables already created, skipping table creation process");

				int success=0;
		        PreparedStatement pstmt = con.prepareStatement("INSERT INTO Book VALUES(?,?)");
		        pstmt.setString(1, bookId);
		        pstmt.setBytes(2,bytes);    //Storing binary data in blob field.
		        success = pstmt.executeUpdate();
		        if(success>=1)  System.out.println("Book Stored");

		         writer.println("<br/> Book Successfully Stored");

	    } catch (FileNotFoundException fnf) {
	        writer.println("You  did not specify a file to upload");
	        writer.println("<br/> ERROR: " + fnf.getMessage());

	    } catch (SQLException e) {
			// TODO Auto-generated catch block
		} finally {

	        if (pdfFileBytes != null) {
	        if (writer != null) {



Running the above example


Fileupload form

Type Book Id and select Pdf file and upload

Fileupload form2

Fileupload result

Fileupload form1

Fileupload error

Reference : File Upload

Download the above application at fileupload.war



You may also like

Leave a Reply