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:

mysql-5.1.10.jar
javax.servlet-api-3.1.0.jar

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.

fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="FileUpload" enctype="multipart/form-data" >
<table>
        <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>
        </tr>
        <tr>
        <td colspan="2">
            <input type="submit" value="Upload" name="upload" id="upload" /> </td>
        </tr>
   </table>
        </form>
    </body>
</html>

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.

FileUploadPdf.java

package net.javaonline.servlet.fileupload;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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;

@WebServlet("/FileUpload")
@MultipartConfig
public class FileUploadPdf extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,  HttpServletResponse response)       throws ServletException, IOException {
	    response.setContentType("text/html;charset=UTF-8");

	    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");
		    		   return;
     	    }

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

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

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

	        Connection  con=null;
	         Statement stmt=null;

		       try {
		    	     Class.forName("com.mysql.jdbc.Driver");
		    	     con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","*******");
		          } catch (Exception e) {
		    	  		System.out.println(e);
		                System.exit(0);
		                      }

		      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");
		         con.close(); 

		         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
			e.printStackTrace();
		} finally {

	        if (pdfFileBytes != null) {
	        	pdfFileBytes.close();
	        }
	        if (writer != null) {
	            writer.close();
	        }
	    }

	}

} 

Running the above example

http://localhost:8080/TestWeb/fileUpload.jsp

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

Be the First to Comment!