Inserting Image in Database Using Java

This application inserts an image into a database (SQL Server 2008). That is quite a common task these days. We need to create an application capable of storing textual as well as binary data from the application to the database and also to get the data from the database into our front end. Well talking about this application it is made on core Java. My next example will be covering the image store in database using servlets or JSP.
 
In this application, we will be using Swing and AWT packages for creating the front end and our database is SQL Server 2008. For this example, we will be using an Employee Table with the following structure.
  1. CREATE TABLE [dbo].[Employee](  
  2. [EmpID] [int] IDENTITY(1,1) NOT NULL,  
  3. [EName] [varchar](30) NOT NULL,  
  4. [EAddress] [varchar](40) NOT NULL,  
  5. [ESalary] [floatNULL,  
  6. [EPhoto] [varbinary](maxNULL  
  7. )  
And our front end screenshot is like the following:
 
Inserting Image in Database using Java 
 
On the click of the browse button we are allowing the user to select an image file by applying a filter on FileChooser. If the user does not upload an image file then we are uploading a default image for it that is stored in src/resources/blank-image.png .
 
The following is the source code for it.
  1. /* 
  2.  
  3.  * To change this license header, choose License Headers in Project Properties. 
  4.  
  5.  * To change this template file, choose Tools | Templates 
  6.  
  7.  * and open the template in the editor. 
  8.  
  9. */package insertimagedb;  
  10. import java.sql.*;  
  11. import java.awt.*;  
  12. import javax.swing.*;  
  13. import java.awt.event.*;  
  14. import javax.swing.filechooser.FileSystemView;  
  15. import java.io.*;  
  16. import java.net.URL;  
  17. import javax.swing.filechooser.FileNameExtensionFilter;  
  18.   
  19. /** 
  20.  * 
  21.  * @author Vishal.Gilbile 
  22.  */  
  23. public class EmpApp extends JFrame implements ActionListener {  
  24.   
  25.     JTextField txtName, txtAdd, txtSalary, txtPath;  
  26.     JLabel lblName, lblAdd, lblSalary, lblPath;  
  27.     JButton btnSave, btnBrowse;  
  28.     JFileChooser fileChooser;  
  29.     JPanel pobj, innerPanel;  
  30.     GridBagConstraints gc = new GridBagConstraints();  
  31.   
  32.     public EmpApp() {  
  33.   
  34.         lblName = new JLabel("Name:");  
  35.         lblAdd = new JLabel("Address:");  
  36.         lblSalary = new JLabel("Salary:");  
  37.         lblPath = new JLabel("Select Photo:");  
  38.         txtName = new JTextField(15);  
  39.         txtAdd = new JTextField(15);  
  40.         txtSalary = new JTextField(15);  
  41.         txtPath = new JTextField(15);  
  42.         txtPath.setText("No File Uploaded");  
  43.   
  44.         btnSave = new JButton("Save");  
  45.         btnSave.addActionListener(this);  
  46.         btnBrowse = new JButton("Browse");  
  47.         btnBrowse.addActionListener(this);  
  48.   
  49.         pobj = new JPanel();        pobj.setLayout(new GridBagLayout());  
  50.   
  51.         gc.fill = GridBagConstraints.HORIZONTAL;  
  52.         gc.gridy = 0;  
  53.         gc.gridx = 0;  
  54.         gc.weighty = gc.weightx = 0.5;  
  55.         pobj.add(lblName, gc);  
  56.   
  57.         gc.fill = GridBagConstraints.HORIZONTAL;  
  58.         gc.gridx = 1;  
  59.         gc.gridy = 0;  
  60.         gc.weighty = gc.weightx = 0.5;  
  61.         pobj.add(txtName, gc);  
  62.   
  63.         gc.fill = GridBagConstraints.HORIZONTAL;  
  64.         gc.gridx = 0;  
  65.         gc.gridy = 1;  
  66.         gc.weighty = gc.weightx = 0.5;  
  67.         pobj.add(lblAdd, gc);  
  68.   
  69.         gc.fill = GridBagConstraints.HORIZONTAL;  
  70.         gc.gridx = 1;  
  71.   
  72.         gc.gridy = 1;  
  73.         gc.weighty = gc.weightx = 0.5;  
  74.         pobj.add(txtAdd, gc);  
  75.   
  76.         gc.fill = GridBagConstraints.HORIZONTAL;  
  77.         gc.gridx = 0;  
  78.         gc.gridy = 2;  
  79.         gc.weighty = gc.weightx = 0.5;  
  80.         pobj.add(lblSalary, gc);  
  81.   
  82.         gc.fill = GridBagConstraints.HORIZONTAL;  
  83.         gc.gridx = 1;  
  84.         gc.gridy = 2;  
  85.         gc.weighty = gc.weightx = 0.5;  
  86.         pobj.add(txtSalary, gc);  
  87.   
  88.         gc.fill = GridBagConstraints.HORIZONTAL;  
  89.         gc.gridx = 0;  
  90.         gc.gridy = 3;  
  91.         gc.weighty = gc.weightx = 0.5;  
  92.         pobj.add(lblPath, gc);  
  93.   
  94.         gc.fill = GridBagConstraints.HORIZONTAL;  
  95.         gc.gridx = 1;  
  96.         gc.gridy = 3;  
  97.         gc.weighty = gc.weightx = 0.5;  
  98.         pobj.add(txtPath, gc);  
  99.   
  100.         gc.fill = GridBagConstraints.HORIZONTAL;  
  101.         gc.gridx = 2;  
  102.         gc.gridy = 3;  
  103.         gc.weighty = gc.weightx = 0.5;  
  104.         pobj.add(btnBrowse, gc);  
  105.   
  106.         gc.fill = GridBagConstraints.REMAINDER;  
  107.         gc.gridx = 1;  
  108.         gc.gridy = 4;  
  109.         gc.weighty = gc.weightx = 0.5;  
  110.         pobj.add(btnSave, gc);  
  111.   
  112.         getContentPane().add(pobj);  
  113.         setSize(360180);  
  114.         setVisible(true);  
  115.         setResizable(false);  
  116.         setLocation(new Point(320240));  
  117.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  118.   
  119.     }  
  120.   
  121.     /** 
  122.      * This function is used for inserting image into Employee Table 
  123.      * 
  124.      * @param imagePath filePath or profile Photo that needs to be saved 
  125.      */  
  126.     private void SaveImage(String imagePath) {  
  127.         try {  
  128.             byte[] rawBytes = null;  
  129.             FileInputStream fis = null;  
  130.   
  131.             if (imagePath.equals("No File Uploaded")) {  
  132.                 ClassLoader cl = this.getClass().getClassLoader();  
  133.                 URL resouces = cl.getResource("resources/blank-image.png");  
  134.                 imagePath = resouces.getFile();  
  135.             }  
  136.   
  137.             File fileObj = new File(imagePath);  
  138.             fis = new FileInputStream(fileObj);  
  139.             float salary = Float.parseFloat(txtSalary.getText());  
  140.   
  141.             //loading the JdbcOdbc driver for Sql Operations  
  142.             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  143.             //create and specify the DSN as myCon. and since my sql is using windows  
  144. authentication that's why i'm not ing  
  145.             //username and word as the second and third parameter in the getConnectionMethod of DriverManager class  
  146.             Connection con = DriverManager.getConnection("jdbc:odbc:myCon""""");  
  147.             PreparedStatement st = con.prepareStatement("insert into Employee(EName,EAddress,ESalary,EPhoto) values(?,?,?,?)");  
  148.             st.setString(1, txtName.getText());  
  149.             st.setString(2, txtAdd.getText());  
  150.             st.setFloat(3, salary);  
  151.             //st.setBinaryStream(4, fis);  
  152.             int imageLength = Integer.parseInt(String.valueOf(fileObj.length()));  
  153.             rawBytes = new byte[imageLength];  
  154.             fis.read(rawBytes, 0, imageLength);  
  155.             //st.setBinaryStream(4, (InputStream) fis, imageLength);  
  156.             st.setBytes(4, rawBytes);  
  157.             int count = st.executeUpdate();  
  158.             if (count > 0) {  
  159.                 JOptionPane.showMessageDialog(this"Data Saved Successfully");  
  160.             } else {  
  161.                 JOptionPane.showMessageDialog(this"Error Saving Data");  
  162.             }  
  163.         } catch (HeadlessException | IOException | ClassNotFoundException | NumberFormatException | SQLException ex) {  
  164.             JOptionPane.showMessageDialog(this, ex.getMessage());  
  165.         }  
  166.     }  
  167.    
  168.     /** 
  169.      * ActionPerformed Event used for handling button Click Event 
  170.      * 
  171.      * @param e ActionEvent Object 
  172.      */  
  173.     @Override  
  174.     public void actionPerformed(ActionEvent e) {  
  175.   
  176.         JButton btn = (JButton) e.getSource();  
  177.   
  178.         if (btn.equals(btnBrowse)) {  
  179.   
  180.             fileChooser = new JFileChooser("C:\\", FileSystemView.getFileSystemView());  
  181.             fileChooser.setFileFilter(new FileNameExtensionFilter("Image Files""jpg""png""tif""gif""bmp"));  
  182.             int returnVal = fileChooser.showOpenDialog(pobj);  
  183.             if (returnVal == JFileChooser.APPROVE_OPTION) {  
  184.                 String fileName = fileChooser.getSelectedFile().getName();  
  185.                 String extension = fileName.substring(fileName.lastIndexOf("."));  
  186.                 if (extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".png")  
  187.                         || extension.equalsIgnoreCase(".bmp") || extension.equalsIgnoreCase(".tif")  
  188.                         || extension.equalsIgnoreCase(".gif")) {  
  189.                     txtPath.setText(fileChooser.getSelectedFile().getPath());  
  190.                 } else {  
  191.                     JOptionPane.showMessageDialog(this"Kindly Select Image File Only",  
  192. "Error", JOptionPane.ERROR_MESSAGE);  
  193.                 }  
  194.             } else {  
  195.                 txtPath.setText("No File Uploaded");  
  196.             }  
  197.         }  
  198.  else if (btn.equals(btnSave)) {  
  199.             SaveImage(txtPath.getText());  
  200.         }  
  201.     }  
  202.     /** 
  203.      * @param args the command line arguments 
  204.      */  
  205.     public static void main(String[] args) {  
  206.         EmpApp objEmp = new EmpApp();  
  207.     }  
  208. }  
The following is the output:
 
 
 
In the preceding case since the user is selecting an image, that image will be stored inside SQL Server.
 
Now for the second case if the user doesn't select any image then the default image should be stored. The following is the output for it.