Friday, November 25, 2011

Upload, Save and Retrieve Image

  This article shows you how to upload,save and retrieve image in asp.net using c#. Basically we can do this in two way.The first one is we can save the image in any specific folder and in database save the path and to retrieve it just bind the path to image url. And in another way we can save the image in binary format in database.Now at first place the image control, file upload control and button in your aspx page.

<asp:Image ID="imgMem" runat="server" Height="116px" BorderColor="Black"  BorderStyle="Double" ImageUrl="~/Images/userimage.jpg" Width="150px" EnableTheming="False" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click"  Text="Upload" />

In button click event write down the code given below.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            path = Server.MapPath("~/Library/Images/");
            FileUpload1.SaveAs(path+FileUpload1.FileName);
            picnm = FileUpload1.FileName;
           /* If Path exists then set path to ImageUrl & hold the value on ViewState */
            ViewState["picnm"] = picnm;
            imgMem.ImageUrl = "~/Library/Images/" + FileUpload1.FileName;
        }
    }

In database define the field as varchar. And  save it in your own way.
  cmd.Parameters.AddWithValue("@img",ViewState["picnm"].ToString());

To retrieve the image fetch the field value and bind it to image url.
 imgMem.ImageUrl = "~/Library/Images/" + dr["MemPic"].ToString();

Now to save image in binary format write given code in button's click event
  if (FileUpload1.HasFile)
            {
                 // Create a byte[] from the input file
                len = FileUpload1.PostedFile.ContentLength; // Here len is integer
                if(len > 409600)
                {
                    CloseWindow = "alert('Picture size is too large.Maximum file size is 400KB.');";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel_St, this.UpdatePanel_St.GetType(),       "CloseWindow", CloseWindow, true);
                    return;
                }
                pic = new byte[len]; //pic is an array of byte type
                FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
                ViewState["pic"] = pic;
                Session["img"] = pic;
                imgMem.ImageUrl = "GetImgBefSave.aspx";

            
            }

To retrieve the image before save create a blank web form and write down the below code in its cs file.

public partial class Library_GetImgBefSave : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindImg();
    }
    public void BindImg()
    {
        byte[] pic = (byte[])Session["img"];
        Response.BinaryWrite(pic);
    }
}

Now to save the image write down the code given below.
  byte[] img = (byte[])ViewState["pic"];
  query = "INSERT INTO [dbo].[test] ([pic]) VALUES (@img)";
  SqlCommand cmd = new SqlCommand(query,con);
  cmd.CommandType = CommandType.Text;
  cmd.Parameters.AddWithValue("@img", img);
  if (con.State == ConnectionState.Closed)
        con.Open();
  cmd.ExecuteNonQuery();
  con.Close();

To retrieve the image create a new blank web form.In the code behind write down the below code.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Library_getimg : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EduComERPConnectionString"].ConnectionString);
    string query = null;
    string id = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        id = Request.QueryString["ID"];
        if (!IsPostBack)
        {
            GetImg();
        }
    }
    public void GetImg()
    {
        query = "SELECT [MemPic] FROM [dbo].[tbl_LibMemInfo] where [Lib_Id]=" + id + "";
        SqlCommand cmd = new SqlCommand(query,con);
        cmd.CommandType = CommandType.Text;
        if (con.State == ConnectionState.Closed)
            con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            if (dr["MemPic"].ToString() != "")
            {
                byte[] img = (byte[])dr["MemPic"];
                Response.BinaryWrite(img);
            }
        }
        dr.Close();
        con.Close();
    }
}


Now bind the address of this web form to image url.

 imgMem.ImageUrl = "getimg.aspx?ID=" + dr["Lib_Id"].ToString();
    


No comments:

Post a Comment