Image uploading and saving into MySQL and then display image

Let us look at how to upload an image into MySQL DB and then display the image using JSP, Servlet and MySQL database.

Java Servlet API doesn't provide any method to handle file upload. So, we have to depend on a library provided by third parties. In this post I am going to use Commons Fileupload library provided by Apache Foundation.


•    commons-io-2.0.jar ( http://commons.apache.org/io/download_io.cgi )
•    commons-fileupload-1.2.2.jar ( http://commons.apache.org/fileupload/download_fileupload.cgi )

Now let us starts with a JSP file which has the following fields First Name, Last Name and Portrait Photo.

Upload.jsp
<%--
 *
 * Author           : Sanjeev Kulkarni
 * Project          : WebLearning
 * Created On       : 03-Jul-2013 3:12:44 PM
 *
--%>


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    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">
<title>File Upload to Database Demo</title>
</head>
<body>
    <center>
        <h1>File Upload to Database Demo</h1>
        <form action="displayServlet" method="get">
            <table>
                <tr>
                    <td>
                        <div style="background: none repeat scroll 0 0 ghostwhite; height: 150px; width: 150px;">
                            <img src="displayServlet?id=13" height="150px" width="150px" alt="ProfilePic">
                    </div>
                    </td>
                </tr>
            </table>
        </form>
        <form method="post" action="uploadServlet" enctype="multipart/form-data">
            <table border="0">
                <tr>
                    <td>First Name: </td>
                    <td><input type="text" name="firstName" size="50"/></td>
                </tr>
                <tr>
                    <td>Last Name: </td>
                    <td><input type="text" name="lastName" size="50"/></td>
                </tr>
                <tr>
                    <td>Portrait Photo: </td>
                    <td><input type="file" name="photo" size="50"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>


Once you upload the image and click on Save button, request will be sent to FileUploadDBServlet which process the request and stores the image into MySQL db.

FileUploadDBServlet.java 
 
package com.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
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;

/**
 * Servlet implementation class FileUploadDBServlet
 */
@WebServlet("/FileUploadDBServlet")
@MultipartConfig(maxFileSize = 10177215) // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadDBServlet() {
        super();
    }

    private String dbURL = "jdbc:mysql://localhost:3306/web_learning";
    private String dbUser = "root";
    private String dbPass = "root";
     
    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
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());
             
            // obtains input stream of the upload file
            inputStream = filePart.getInputStream();
        }
         
        Connection conn = null; // connection to the database
        String message = null;  // message 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);
            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) {
                message = "File uploaded and saved into database";
            }
        } catch (SQLException ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            // sets the message in request scope
            request.setAttribute("Message", message);
             
            // forwards to the message page
            getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
        }
    }
}


So we are done with uploading of the image. So simple isn’t it! Now you have the image stored into the database, next question is how to retrieve the image? We know little bit about the TNIYBLOB,BLOB,MEDIUMBLOB,LONGBLOB and the content of these types are stored in the db as a binary object.

•    TINYBLOB: maximum length of 255 bytes
•    BLOB: maximum length of 65,535 bytes
•    MEDIUMBLOB: maximum length of 16,777,215 bytes
•    LONGBLOB: maximum length of 4,294,967,295 bytes



Note that if you generate your table from the JPA annotations, you can "control" the type MySQL will use by specifying the length attribute of the Column, for example:


@Lob 
@Basic(fetch = FetchType.LAZY)
@Column(length=100000)
private byte[] picture;


Depending on the length, you'll get:
       0 < length <=      255  -->  `TINYBLOB`
     255 < length <=    65535  -->  `BLOB`
   65535 < length <= 16777215  -->  `MEDIUMBLOB`
16777215 < length <=    2³¹-1  -->  `LONGBLOB`


In Open JPA if we do not provide FetchType, I was getting some warnings whenever I was running the enhancer tool for enhancing the entities. Now don’t worry about the JPA concept, we will concentrate just on servlet, jdbc.



DisplayServlet.java
 
package com.servlet;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DisplayServlet
 */
@WebServlet("/DisplayServlet")
public class DisplayServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    public void init() throws ServletException {

    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DisplayServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String imageId = request.getParameter("id");
        System.out.println(imageId);
        InputStream sImage;

        // Check if ID is supplied to the request.
        if (imageId == null) {
            // Do your thing if the ID is not supplied to the request.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web_learning", "root","root");
            stmt = conn.prepareStatement("select * from contacts where contact_id=" + imageId);
            rs = stmt.executeQuery();
            if(rs.next()){
                System.out.println("Inside RS");
                byte[] bytearray = new byte[1048576];
                int size=0;
                sImage = rs.getBinaryStream(4);
                response.reset();
                response.setContentType("image/jpeg");
                while((size = sImage.read(bytearray)) != -1 ){
                    response.getOutputStream().
                    write(bytearray,0,size);
                }
            }

        } catch (Exception e){
            e.printStackTrace();
        }
    }
}




For displaying image in any of your JSP page you need to pass the id like below:

<img src="displayServlet?id=1" height="150px" width="150px" alt="ProfilePic">

There is one more method for displaying the image from DB. You can refer to the following post for the same: http://balusc.blogspot.in/2007/04/imageservlet.html#ImageServletServingFromDatabase

Hope this post helps for your development activities. See you then,

Sanjeev Kulkarni

Home Surveillance – Real time Home monitoring using Skype

Consider that you are on a day out with your family and then you want to know how safe your house is without spending much! – What to do? And how to do? How to avoid spending money over home surveillance? If any of the questions arises in your mind then I have simple solution for you. After making this blog post into action you can relax and spend your time on your vocations without worrying much. This idea even helps to monitor your babies at home!

Isn’t it sounds great? So let’s get started with Home Surveillance set up:

What you need to have:
  • Laptop (or desktop) at home with webcam.
  • Internet with moderate bandwidth and speed.
  • Smartphone.
Procedure:
  • Download and install Skype from (http://www.skype.com/en/download-skype/skype-for-computer) on your home computer and create an account (let’s say home_skype).
  • Download and install Skype from (http://www.skype.com/en/download-skype/skype-for-mobile/) on your smartphone and create another account (let’s say mobile_skype).
  • Add each other’s Skype account into respective friend list.
  • In your home_skype account, go to Tools->Options->Privacy, click on “show advanced options” and set the following:
  • Set “Allow calls from” to “people in my contact list only”
  • Set “Automatically receive video and share screens with” to “people in my contact list only

A screenshot of the settings:



That’s it. All the settings are done. You don’t have to do these on your mobile_skype account

Typical use case scenario:

Login to Skype into the home laptop (home_skype account) and place the laptop in your house in such a way that it faces the entrance (or any place that you want to monitor). Login to mobile_skype account on your smartphone and make a video call to the home_skype account.

Due to the above settings, the home laptop Skype account will automatically accept the call and start streaming the video to your smartphone and thus you will be able to monitor your home in real time and on demand basis by making video call to the home account any number of times a day.

Alternate components/devices:

If you do not have a smartphone, you can login to the mobile_account from any laptop/desktop and make a video call to home account to monitor in real time and on demand.

Alternate use cases:

-It can be used to monitor baby or the babysitter so that working parents can work peacefully in offices instead of worrying about issues like these:

http://articles.timesofindia.indiatimes.com/2009-11-06/bangalore/28106781_1_nanny-baby-parents

Tips:

-To save power, switch off the laptop screen and set the processor to low power mode.

-Ensure that it does not go into sleep mode after sometime.

-Ensure that you have an unlimited home broadband plan because being logged into skype for long time (even if you do not make calls) consumes bandwidth.

-If your webcam does not have sufficient coverage, you can fix convex lens in front of the camera to increase its coverage up to 180 degrees. Even door viewers like these can be used:

http://www.ebay.in/itm/Door-Viewer-Peephole-for-Home-Metal-180-Degree-/261232970230?pt=LH_DefaultDomain_203&hash=item3cd2b2c9f6&_uhb=1#ht_3951wt_1139

Uttarakand Flood



Flood affected people might have wished that even Pakistani/Chinese politicians might have helped them very well than our so called great government.  Bharat Nirman kaha ho raha hai? They are spending lacks of millions of crores over this Bharat Nirman advertisement. For what? Is it necessary?   


About Uttarakhand Calamity:
Kedaranath Temple

God Shiva statue in flood

Flood affected road

Flood of Uttarakand
Building collapsed due to heavy rain

1) Uttarakhand CM off to switzerland.
Flood effects in Uttarakand

2) RG celebrating in Spain ( #WhereisPappu ?). Don’t get confused RG means Rahul Ghandhi as people say but actually it’s Rahul Vinci as in his Italian passport. And politicians of our great UPA members call him as future Prime Minster of India? People just think at least once is he any way capable of holding that post? Doesn’t your blood boil over this? If no you should think over your patriotism. Is he a youth icon? What is the age you call a person a youth? He is crossed 40 and still a youth icon? Please don’t just agree with what people around you say. Open your eyes of knowledge my dear citizens.

Pappu came back from his luxury holidays in Europe after finishing as planned instead of boycotting his holidays while delaying rescue operations because Sonia madam wished his son should flag the operations. Playing politics over the Uttarakand flood is the worst’s of the worst days of my life!
Indian Army rescue camp

3) MMS/Sonia aerial survey costs vital rescue hours as entire air traffic is halted for hours.

4) Khurshid visiting Iraq with hundreds thousands of Crores (dollars) in aid, Bharat Nirman ads run in hundreds of crores but this devastating calamity is allocated mere 144 Crores.

5) Four choppers for Sonia's Rajasthan trip, but shortage of choppers to rescue people.

6) People asked to donate to PM fund even while available supplies lay undistributed.

7) Complete government machinery failure. Only hope being the Army, the RSS, Baba Ramdev and other such local volunteers.

8) Uttarakand CM refuses Narendra Modi’s offer of 24 choppers for rescue operation? For what sake Mr.Uttarakand CM? People are losing their lives without any food for survival and you people are playing politics over this issue also? Shame on you Mr.Uttarakand CM. Why you have not welcomed that helping hand it would have resulted in faster evacuation of affected people.
All of this while thousands, mostly Hindus and some Sikhs, are dying there of hunger, cold and injuries - and then this Manish Tiwary has the audacity to come on national TV and say "This is not the time to point fingers" !!!
Oh we're sorry. We should have complained about this to govt. of China or Pakistan maybe. We forgot that the govt of India is too good for its people. Well yes, after this is over you will wash away your failures with some match fixing or movie star suicide case. Just the way you did with Coal/Chopper scam. So when will it be really ok for people of India to point fingers at your government sir?
 
Please keep us posted on whenever you are comfortable with it.


May God save each and everyone affected in this bad situation...Hats off to Indian Army, RSS and the people who helped...
Indian Army Rescue operations. Hats off to them for their service. Not minding about their lives they saved many.

Indian Army Rescue operations. Hats off to them for their service. Not minding about their lives they saved many.

Google is helping to find the people. You can utilize the link below to find any person missing or provide the info if you found any one.

http://google.org/personfinder/2013-uttrakhand-floods

Hope that there should not be any scam of looting donation money by this government and all the money goes towards relief activities...Can’t say but I just hope...