Friday 24 May 2013

How to Upload Image in asp.net having dataType in database is Image.



Description:-

 In this Example we explain that How to store Image in database using “Image data type  or  how we can store image in the database. the main need to store image in database occur, while there is a issue of security. I mean to says that we can store the image of the signature of the people or human, because of the banking security or any other Department. To store the image in the database we have to use byte[] array. First when upload image by user using file upload control then I will convert the image into byte array[] and then it will store the image in the database..This type of example is very useful when we want to directally add the Image in Byte[] Format not the path of image in database.

       in which we can easily upload any type of Image like .jpg,.png,.jpeg etc... and easily Retrieve from the Database and Display it. 

Here is a code to Convert image into byte[] before we uploading it to the Database are as follow

byte[] imageByte = new byte[flUpload.PostedFile.InputStream.Length + 1];

        flUpload.PostedFile.InputStream.Read(imageByte, 0, imageByte.Length);

        _sqlCommand.Parameters.AddWithValue("Image", imageByte);

When we Retrieve Image From database we have First Type cat like

//we need to typecast to byte[] before feeding it to BinaryWrite method.

        if (_sqlDataReader.Read())

        {

            Response.BinaryWrite((byte[])_sqlDataReader["photo"]);

        }

the main Advantages of this example is the image is stored in database so you have not to maintain it's path. and the Disadvantage is that you have to Required High Database Size Because wall Image is stored in the database.

To Show Example of How to Upload File in MVC Application then click here upload Image and bind to Gridview in MVC

How to Handle Concurrency in Linq to Sql Concurrency Handle in Linq to SQL

Generate Random Password Autogenerate Unique Password


upload.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <p><b><asp:Literal ID="lit_storeImage" runat="server">Store Image to DB</asp:Literal></b></p>
<asp:Label ID="lbl_SelectFile" runat="server" Text="Select an image file to upload: "></asp:Label>
<asp:FileUpload ID="FileUpload_images" runat="server" />
<br />
<br />
<asp:Button ID="btn_storeImageInDB" runat="server"
onclick="btn_storeImageInDB_Click" Text="Store Image in DB" />
</div>
<hr />
<div>
<p><b><asp:Literal ID="lit_retrieveImage" runat="server">Retrieve Image from DB</asp:Literal></b></p>
<asp:Image ID="imgFromDB" runat="server" AlternateText="No Image"
GenerateEmptyAlternateText="True" Height="80px" Width="80px" />
<br />
<br />
<asp:Button ID="btn_retrieveImageFromDB" runat="server"
onclick="btn_retrieveImageFromDB_Click" Text="Retrieve Image from DB" />
    </div>
    </form>
</body>
</html>




upload.aspx.cs:-


using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;
using System.Data.SqlClient;

public partial class upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private void StoreImageinDB(FileUpload flUpload)
    {
        SqlConnection _sqlConnection = new SqlConnection();
        SqlCommand _sqlCommand = new SqlCommand();

        _sqlConnection.ConnectionString = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";

        _sqlConnection.Open();

        _sqlCommand.Connection = _sqlConnection;

        string SQLString = "Insert into v_emp (empname,salary,desig,photo) values (@imgDescription,@salary, @type, @Image)";
        _sqlCommand.CommandText = SQLString;

        _sqlCommand.Parameters.AddWithValue("@imgDescription", "Humpback Whale");
        _sqlCommand.Parameters.AddWithValue("@salary", "5000");
        _sqlCommand.Parameters.AddWithValue("@type", "jpeg");

        //create byte[] of length equal to the inputstream of the selected image.
        byte[] imageByte = new byte[flUpload.PostedFile.InputStream.Length + 1];
        flUpload.PostedFile.InputStream.Read(imageByte, 0, imageByte.Length);
        _sqlCommand.Parameters.AddWithValue("Image", imageByte);

        _sqlCommand.ExecuteNonQuery();

        _sqlConnection.Close();
    }

    protected void btn_storeImageInDB_Click(object sender, EventArgs e)
    {
        FileUpload _fileUpload = (FileUpload)this.FindControl("FileUpload_images");
        if (_fileUpload.HasFile)
        {
            StoreImageinDB(_fileUpload);
        }
        else
        {
            Response.Write("Please select an image file");
        }
    }



    protected void btn_retrieveImageFromDB_Click(object sender, EventArgs e)
    {
        RetrieveImageFromDB();
    }

    private void RetrieveImageFromDB()
    {
        imgFromDB.ImageUrl = "ImageURL.aspx";
    }
}



ImageURL.aspx.cs:-

using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;
using System.Data.SqlClient;

public partial class ImageURL : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection _sqlConnection = new SqlConnection();
        SqlCommand _sqlCommand = new SqlCommand();

        _sqlConnection.ConnectionString = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";
        _sqlConnection.Open();
        _sqlCommand.Connection = _sqlConnection;

        string SQLString = "select  * from v_emp";
        _sqlCommand.CommandText = SQLString;

        SqlDataReader _sqlDataReader = _sqlCommand.ExecuteReader();

        //we need to typecast to byte[] before feeding it to BinaryWrite method.
        if (_sqlDataReader.Read())
        {
            Response.BinaryWrite((byte[])_sqlDataReader["photo"]);
        }

        _sqlDataReader.Close();
        _sqlConnection.Close();

    }
}



0 comments:

Post a Comment