Monday, 19 November 2012

IMAGE UPLOAD INTO SQL DATABASE

CREATE A TABLE IN SQL

Create table uploadimage
(

  [ImageID] [int] IDENTITY(1,1) NOT NULL,
[Images] [image] NULL,
[ImageName] [varchar](max) NULL,

)

IN THE ASPX PAGE

   <form id="form1" runat="server">
        <div>
        <asp:Label ID="lblfu" runat="server" Text="Image Upload"></asp:Label>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
     
        <asp:Label ID="lblimgname" runat="server" Text="Image Name" ></asp:Label>
        <asp:TextBox ID="txtimgname" runat="server"></asp:TextBox>
        <br />
   
        <asp:Button ID="btnupload" runat="server" Text="Upload" onclick="btnupload_Click" />
        <asp:Label ID="lblmsg"  runat="server" Text=""></asp:Label>
        <br/>
     
    </div>
    </form>

IN THE ASPX.CS PAGE(In the Upload button click event)

    static string constr = ConfigurationManager.ConnectionStrings["stringname"].ConnectionString;
    SqlConnection con = new SqlConnection(constr); //configuring connection string from the webconfig


 protected void btnupload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
            HttpPostedFile myimg = FileUpload1.PostedFile;
            myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
            SqlCommand cmd = new SqlCommand("insert into pimage(Images,ImageName) values          (@images,@imageName)", con);


            SqlParameter uploadimg = new SqlParameter("@images", SqlDbType.Image);
            uploadimg.Value = img;
            cmd.Parameters.Add(uploadimg);

            SqlParameter imgname = new SqlParameter("@imageName", SqlDbType.VarChar, 100);
            imgname.Value = txtimgname.Text;
            cmd.Parameters.Add(imgname);


            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            lblmsg.Text = "Image uploaded";
            txtimgname.Text = "";
     
        }
        else
        {
            lblmsg.Text = "Image upload unsuccessfull";
        }
    }


No comments:

Post a Comment

back to top