Monday, July 23, 2018

How to store image or file save in database in binary datatype / image data type in sql server | Sradha WebCreations


How to store image or file save in database in binary datatype / image data type in sql server

how to store image in binary format in  MS Sql Server Database 


 http://sradhawebcreations.com/


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

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

       Enter ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
       Enter Name&nbsp;&nbsp; <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        Select image&nbsp;  <asp:FileUpload ID="FileUpload1" runat="server" /><br />
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" /><br />

       <asp:Image ID="Image1"  runat="server" Height="137px" Width="130px" /><br />
       
        <asp:DropDownList ID="TextBox3" runat="server">
        </asp:DropDownList>
       
        <asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />

    </div>
    </form>
</body>
</html>

 http://sradhawebcreations.com/
HttpHandler.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.WebControls;
using System.Configuration;

public partial class HttpHandler : System.Web.UI.Page
{
    //static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    static SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldropdown();
        }
    }

    public void filldropdown()
    {
        SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        TextBox3.Items.Clear();
        if (dr.HasRows)
        {
            //TextBox3.DataSource = dr["EmpID"].ToString();
            //TextBox3.DataBind();

            while (dr.Read())
            {
                TextBox3.Items.Add(dr["EmpID"].ToString());
            }
        }
        con.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Tbl_Emp values(@id,@name,@image)",con);
        cmd.Parameters.AddWithValue("@id", TextBox1.Text);
        cmd.Parameters.AddWithValue("@name", TextBox2.Text);

        int img = FileUpload1.PostedFile.ContentLength;

        byte[] msdata = new byte[img];

        FileUpload1.PostedFile.InputStream.Read(msdata,0,img);

        cmd.Parameters.AddWithValue("@image", msdata);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.ExecuteNonQuery();

        con.Close();

        filldropdown();

        Response.Write("Data Saved ....");

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
        cmd.Parameters.AddWithValue("@id", TextBox3.Text);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows && dr.Read())
        {
            TextBox1.Text = dr["EmpID"].ToString();
            TextBox2.Text = dr["EmpName"].ToString();
            Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
        }
        else
        {
            Response.Write("Record With This ID Note Found");
        }
       con.Close();

    }
}
Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;

public class Handler : IHttpHandler {

  //  static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    static SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
    public void ProcessRequest (HttpContext context) {
       // context.Response.ContentType = "text/plain";
       // context.Response.Write("Hello World");
        SqlCommand cmd = new SqlCommand("select EmpPic from Tbl_Emp where EmpID=@EmpID",con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.Parameters.AddWithValue("@EmpID", context.Request.QueryString["EmpID"].ToString());
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows && dr.Read())
        {
            context.Response.BinaryWrite((byte[])(dr["EmpPic"]));
        }
      
        con.Close();
       
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}


 http://sradhawebcreations.com/


file save in different name if file is exist in same name by using FileUpload control in asp.net | Sradha Webcreations


file save in different name if file is exist in same name by using FileUpload control in asp.net 

check file in same name before store in ms sql server data base 
 http://sradhawebcreations.com

filesaving.aspx

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

<!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 runat="server">
    <title></title>
    <script type="text/javascript" src="jquery-1.8.2.js"></script>

/*Java script for priview image*/

<script type="text/javascript">
    function showimagepreview(input) {
        if (input.files && input.files[0]) {
            var filerdr = new FileReader();
            filerdr.onload = function (e) {
                $('#imgprvw').attr('src', e.target.result);
            }
            filerdr.readAsDataURL(input.files[0]);
        }
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
     <asp:FileUpload ID="FileUpload1" runat="server" onchange="showimagepreview(this)" />
        <br />
  <asp:Button ID="ButtonSAve" runat="server" onclick="ButtonSAve_Click"  Text="Save" />
<br/>
            <img id="imgprvw" />
<asp:Label ID="UploadStatusLabel" runat="server"Text="Label" Visible="False"></asp:Label>
        <br />
   
    </div>
    </form>
</body>
</html>

 http://sradhawebcreations.com

filesaving.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;


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

    }
    SqlConnection con=new SqlConnection (ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString);

    protected void ButtonSAve_Click(object sender, EventArgs e)
    {
        try
        {
            string FileName = SaveFile(FileUpload1.PostedFile);
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into DATAIMAGE (image) values(@image)", con);


            cmd.Parameters.AddWithValue("image", "Tested Files/" + FileName);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch(Exception ex)
        {
            Response.Write(ex);
           
        }

    }

         string SaveFile(HttpPostedFile file)
    {
        // Specify the path to save the uploaded file to.
      /* string savePath = "D:\\demoData\\demodataa\\Ademodataaa\\Tested Files\\Tested Files\\";*/
        string savePath = "~\\Tested Files\\";

        // Get the name of the file to upload.
        string fileName = FileUpload1.FileName;    // must be declared in the class above

        // Create the path and file name to check for duplicates.
        string pathToCheck = savePath + fileName;

        // Create a temporary file name to use for checking duplicates.
        string tempfileName = "";

        // Check to see if a file already exists with the
        // same name as the file to upload.
        if (fileName.Length == 0)
        {
            fileName = "file Not Exist";
        }
        else
        {
            if (System.IO.File.Exists(Server.MapPath(pathToCheck)))
            {
                int counter = 2;
                while (System.IO.File.Exists(Server.MapPath(pathToCheck)))
                {
                    // if a file with this name already exists,
                    // prefix the filename with a number.
                    tempfileName = counter.ToString() + fileName;
                    pathToCheck = savePath + tempfileName;
                    counter++;
                }

                fileName = tempfileName;

                // Notify the user that the file name was changed.
                UploadStatusLabel.Visible = true;
                UploadStatusLabel.Text = "A file with the same name already exists." +
              "<br />Your file was saved as " + fileName;
            }
        }


        // Append the name of the file to upload to the path.
        savePath += fileName;

        // Call the SaveAs method to save the uploaded
        // file to the specified directory.
        FileUpload1.SaveAs(Server.MapPath(savePath));
        return fileName;
    }
   
}