Sunday, 24 March 2013

How to upload an image into a MySql database and display it in a jsp page using Struts 2 framework.

Before you start you have to know about the Struts 2 file upload interceptors.And here i give my code that i tested.

By including this below tag library into your jsp page you can access the struts tags by using the prefix "s" also you can use your own prefix.Using a logical name must be better.

<%@taglib prefix="s" uri="/struts-tags"%>

This my upload.jsp page for file uploading....

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Upload Image</h1>
        <s:form action="imageload" method="POST" enctype="multipart/form-data">
            <s:file name="img" label="Choose File"/>
            <s:submit value="Upload" name="submit" />
            </s:form>
        <s:form action="view" method="post">
            <s:submit value="view"/>
        </s:form>
        <s:property value="msg"/>
     
    </body>
</html>

Here i have two actions 1 is "imageload" for storing the image into a database.And  another one is "view" for displaying an image from a database into your jsp page.


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action class="pack.Test" name="test">
            <result name="success">upload.jsp</result>
            <result name="error">index.jsp</result>
        </action>
        <action class="pack.Test" name="imageload" method="imageLoad">
            <interceptor-ref name="fileUpload">
            <param name="maximumSize">20971522</param>
            <param name="allowedTypes">image/png,image/gif,image/jpeg,image/pjpeg</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">upload.jsp</result>
            <result name="input">upload.jsp</result>
            <result name="error">upload.jsp</result>
        </action>
        <action class="pack.Test" name="view" method="view">
            <result name="success">view.jsp</result>
            <result name="error">upload.jsp</result>
        </action>
    </package>
</struts>

This is my "struts.xml " file and here i a configure my path to the action class.


package pack;

import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
/**
 *
 * @author ansonfamps
 */
public class Test extends ActionSupport {
    Connection con;
    Statement st;
    PreparedStatement ps;

    public byte[] getB() {
        return b;
    }

    public void setB(byte[] b) {
        this.b = b;
    }
    ResultSet rs=null;
    Blob dimg;
    byte b[]=null;
    int f=0;
    File img;
    String imgFileName,imgContentType;
    String mail,msg;
FileOutputStream fos;
    public File getImg() {
        return img;
    }

    public FileOutputStream getFos() {
        return fos;
    }

    public void setFos(FileOutputStream fos) {
        this.fos = fos;
    }

    
    public void setImg(File img) {
        this.img = img;
    }

    public String getImgFileName() {
        return imgFileName;
    }

    public void setImgFileName(String imgFileName) {
        this.imgFileName = imgFileName;
    }

    public String getImgContentType() {
        return imgContentType;
    }

    public void setImgContentType(String imgContentType) {
        this.imgContentType = imgContentType;
    }
    
    
    public Test() {
    }
    

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
    
    public String execute() throws Exception {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/foto2fame","root","123");
            st=con.createStatement();
            rs=st.executeQuery("select email from user_login");
            while(rs.next())
            {
                if(mail.equals(rs.getString("email")))
                {
                    f=1;
                }
            }
            
        }
        catch(Exception e)
{
            System.out.print("Exception from database connectivity"+ e.getMessage()+"\n"+e.getStackTrace());
}
        if(f==1)
        {
            this.setMsg("Login Success");
            return SUCCESS;
        }
        else
        {
            this.setMsg("Login Failed");
            return ERROR;
        }
    }
    public String imageLoad()
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/foto2fame","root","123");
            ps=con.prepareStatement("update profile set accimg=? where email='ansonfamps'");
            FileInputStream fis=new FileInputStream(img);
            ps.setBinaryStream(1,fis,(int)img.length());
            System.out.println("Rows affected = "+ps.executeUpdate());
            this.setMsg("File Uploaded ");
            return SUCCESS;
        }
        catch(Exception e)
{
            System.out.print("Exception from database connectivity"+ e.getMessage()+"\n"+e.getStackTrace());
            this.setMsg("Failed to upload ");
            return ERROR;
}
        
    }
    public String view()
    {
       try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/foto2fame","root","123");
            st=con.createStatement();
            rs=st.executeQuery("select accimg from profile where email='ansonfamps'");
            while(rs.next())
            {
                dimg=rs.getBlob("accimg");
                f=1;
            }
            b=new byte[(int)dimg.length()];
            b=dimg.getBytes(1,(int)dimg.length());
            HttpServletResponse response=ServletActionContext.getResponse();
            response.setContentType("image/jpeg");
            OutputStream out=response.getOutputStream();
            out.write(b);
            out.flush();
            out.close();
        }
        catch(Exception e)
{
            System.out.print("Exception from database connectivity"+ e.getMessage()+"\n"+e.getStackTrace());
}
        if(f==1)
        {
            this.setB(b);
            return SUCCESS;
        }
        else
        {
            this.setMsg("Login Failed");
            return ERROR;
        }
    }
}


This is my action class called "Test.java" for uploading and displaying image.And here i created two methods view() and imageLoad() for performing the image uploading and displaying operations.


<%@page import="java.io.OutputStream"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <img src="<s:property value="b"/>"/>
    </body>
</html>

And finally this is my "view.jsp" page for display the image from database.

Note:-If you have any doubt please post your comment i'm ready to solve your problems soon.



No comments:

Post a Comment