MY bLOG

Saturday, 23 November 2013

How to upload file and save it in database?

I would like to explain about  upload images and save it in database you have already seen to upload an images .

In database:
create table & stored procedure:
CREATE TABLE [dbo].[photoalbum](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Images] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


GO
stored procedure:
create procedure sp_insert(@Name nvarchar(50),@Images nvarchar(MAX))
as
begin
insert into photoalbum values(@Name,@Images)

end
In .aspx page:

<body>
    <form id="form1" runat="server">
    <div>
    <h2 align="center">Upload and Save</h2>
        <table align="center">
<tr>
<td>
        <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
</td>
       <td>
<asp:TextBox  ID="TXT_NAME" runat="server"></asp:TextBox>
</td>
</tr>
       <tr>
<td>
Image:</td><td><asp:FileUpload ID="fileupload1" runat="server" />
</td>
</tr>
        <tr>
<td colspan="2" align="center">
           <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></td>
</tr>
        </table>
    <asp:Label ID="lbl_text" runat="server"></asp:Label>
    </div>
    </form>
</body>
you can add an Images folder in the solution Explorer
In .aspx.cs page:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class TouploadandView : System.Web.UI.Page
    {
        string strcon=ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
            SqlConnection con=new SqlConnection(strcon);
            if (fileupload1.HasFile)
            {
                if (fileupload1.PostedFile.ContentType == "image/jpeg" || fileupload1.PostedFile.ContentType == "image/gif" || fileupload1.PostedFile.ContentType == "image/x-png" && fileupload1.PostedFile.ContentLength == 1024)
                {
                    string path = "~/Images/" + fileupload1.FileName;
                    fileupload1.SaveAs(Server.MapPath(path));
                  string getfile=path;
                  SqlCommand cmd = new SqlCommand("sp_insert", con);
                    cmd.CommandType=CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Name",TXT_NAME.Text.Trim());
                    cmd.Parameters.AddWithValue("@Images",getfile);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    lbl_text.Text="Image upload successfull";
                    con.Close();
                }
            }
            }
                   catch(Exception ex)
            {
                   lbl_text.Text=ex.Message;


                   }
}
}
}


i hope you understand this article
Happy coding.........