Image Upload & Display : Java/ MySQL ?

This was an interesting topic for most of the people including myself, during the times when, there was a desperation finding code to perform the very action, 'Upload & Display' images with the Java application.

I thought to note it down, so that somebody else won't necessarily have to be desperate anymore reading a zillion articles and websites.

01. In order to this, first create a simple database.

use test;

create table img_Upload(
 nic varchar(10) not null,
        image BLOB,
        constraint pk_img_Upload primary key(nic)
);

Important: There are 2 ways to store images of your application. One is storing the file path & the other, storing image as a blob. I prefer blob here. Because, I've got less number of images & blob helps not to worry about moving the application around without caring about file paths.

02. Now, You can start creating your Java application using any IDE or manual coding. But, you've to include Database Connection class no matter what.

import java.sql.Connection;
import java.sql.DriverManager;

public class Connect {

    Connection con = null;
    String sourceURL = null;

    public Connect(){

        try {
            Class.forName("com.mysql.jdbc.Driver");
            sourceURL = "jdbc:mysql://localhost:3306/test";

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

    public Connection connect(){

        try {
            con = DriverManager.getConnection(sourceURL,"user","mepassword"); // your user name password 

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

    public void close(Connection con){

        if(con!=null){

            try {
                con.close();

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

03. Then, create a jFrame with a 2 labels, button and a text box. (Add extra jFrame to display image from db)


       03.1. Write jLabel mouse clicked event to display JFileChooser & select the image, so that the selected image will be shown in the jLabel.


    private void jlbl_imageMouseClicked(java.awt.event.MouseEvent evt) {


        JFileChooser ch = new JFileChooser();
        ch.showOpenDialog(null);
        try {
            f1 = ch.getSelectedFile(); // create f1 as: static File f1 class variable so that it's accessible in other private methods
            try {
                Image img = ImageIO.read(f1);
                Image newimg = img.getScaledInstance(jlbl_image.getWidth(),jlbl_image.getHeight(), java.awt.Image.SCALE_SMOOTH);
                ImageIcon ik = new ImageIcon(newimg);
                jlbl_image.setIcon(ik);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        
    }

    03.2.  Write button action performed event like follows.

   
private void jbtn_submitActionPerformed(java.awt.event.ActionEvent evt) {

        Connection con = null;
        Connect dbConn = new Connect();
        try {
            con = dbConn.connect();
            FileInputStream fis = null;
            PreparedStatement ps = null;
            con.setAutoCommit(false);
            fis = new FileInputStream(f1);
            ps = (PreparedStatement) con.prepareStatement("insert into img_Upload values(?,?)");
            ps.setString(1,jtxt_usernic.getText().toString());
            ps.setBinaryStream(2,fis,f1.length());
            int stat = ps.executeUpdate();
            con.commit();
            if(stat==1){
                Display(jtxt_usernic.getText().toString()); // this displays image from db
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Hope you've got everything alright. Test run the project. Here's a screen shot of my own output.



Thanks for coming. Have Your Comments.

No comments: