How to Insert files to MySQL blob using Java Servlet

From DeveloperWiki

Jump to: navigation, search

This sample source code demonstrates of inserting file data to MySQL table with blob data type. You have to use Commons FileUpload and MySQL connectorJ for the this sample.

Contents

[edit] MySQL Table Syntax

DROP TABLE IF EXISTS `test`.`images`;
CREATE TABLE  `test`.`images` (
  `image_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `image_data` longblob NOT NULL,
  PRIMARY KEY  (`image_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


[edit] HTML form

<!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=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
    <form name="form_upload" action="Upload" method="POST"  enctype="multipart/form-data">
    <input type="file" name="ufile" value="" />
    <input type="submit" value="Upload" />
</form>
    </body>
</html>

[edit] Upload.java Servlet

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;
 
 
public class Upload extends HttpServlet {
 
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PreparedStatement pst = null;
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;
        try {
 
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
 
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=dba$");
            stmt = conn.createStatement();
 
            FileUpload fup = new FileUpload();
            DiskFileUpload upload = new DiskFileUpload();
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
 
            int count = 0;
            while (iter.hasNext()) {
                count++;
                FileItem item = (FileItem) iter.next();
                File cfile = new File(item.getName());
                File tosave = new File(getServletContext().getRealPath("/temp/"), cfile.getName());
                //item.write(tosave);
                // String file_name = item.getName(); 
                FileInputStream fis = new FileInputStream(tosave);
                int len = (int) tosave.length();
                pst = conn.prepareStatement("INSERT INTO images (image_data)values(?)");
                //image_data column holds LONGBLOB data type
 
                pst.setBinaryStream(1, fis, len);
                int rows = pst.executeUpdate();
            }
 
        } catch (Exception e) {
            System.out.println(e.toString());
        }
 
    }
}

Leave a Reply

Name (required):

Website:

Comment:

[edit] Nikol said ...

Thanks for starting this article

--Nikol 10:42, 27 October 2008 (MST)

[edit] kaleeswara said ...

Hi I am Kaleeswaran from Bangalore.Thanks for Your code.I gone through your it.i having one doubt.I am using struts frame work how to implement this in my project.we are developing banking project,so how do implement your with my project.guide me please.My Email is:kaleeswaranm@gmail.com. Thank you, kaleeswaran,

--kaleeswara 03:17, 2 January 2009 (EST)

[edit] Gulam Abbas said ...

Hi... I am gulam abbas. I am directly uploading the image through JSP when i tested the code on my local server it worked properly but when i using it from server its showing "File Not Found Exception" can you please explain why its happning and how to resolve this. My E-Mail is sgulamabbas@yahoo.com

thanks in Advance.. Regards Gulam Abbas

--Gulam Abbas 05:30, 14 March 2009 (EDT)

[edit] Lalit said ...

Thanks for the help. But I am having problem doing same using JSP if possible help me

--Lalit 10:28, 29 August 2010 (EDT)

[edit] Dinesh said ...

Hi Gulam Abbas, in server side you have to set the correct path. otherwise it cause for Filenot Found Exception

--Dinesh 06:56, 31 August 2010 (EDT)

[[Category:]]