File uploading and Downloading in asp.net

Here we are performing operations like " File Uploading and Downloading From Gridview ".

Table Structure :

ColumnName   Datatype

id           int
f_name   nvarchar(50)
fileSize           int
attachment   varbinary(MAX)
contentType   nvarchar(MAX)


ASPX Code: 


    <table width="100%">
            <tr>
                <td align="center">
                    <table width="50%">
                        <tr>
                            <td>
                                <asp:Label ID="Label3" runat="server" Text="Select"></asp:Label>
                            </td>
                            <td>
                                <asp:FileUpload ID="FileUpload1" runat="server" />
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
                            </td>
                        </tr>
                        <tr><%--DataSourceID="SqlDataSource1"--%>
                            <td align="center" colspan="2">
                                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="true"
                                     DataKeyNames="id" OnSelectedIndexChanged="gvEmp_SelectedIndexChanged"
                                    OnRowCommand="gvEmpSearch_RowCommand" >
                                    <Columns>
                                        <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
                                            SortExpression="id" />
                                        <asp:BoundField DataField="f_name" HeaderText="f_name" SortExpression="f_name" />
                                        <asp:BoundField DataField="fileSize" HeaderText="fileSize" SortExpression="fileSize" />
                                        <asp:TemplateField AccessibleHeaderText="Download">
                                            <HeaderTemplate>
                                                <asp:Label ID ="lblHeader" runat="server" Text ="Attachment"></asp:Label>
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <%-- <asp:HyperLink ID="lnkUrl" runat="server" Target="_blank" Text='<%# Eval("f_name") %>'
                                                    NavigateUrl='<%# Eval("attachment")%>'></asp:HyperLink>--%>
                                                <asp:LinkButton runat="server" CommandArgument="<%# ((GridViewRow)(Container)).RowIndex %>"
                                                    CommandName="name" ID="lnkname" Text='<%# bind("f_name")%>'></asp:LinkButton>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                    </Columns>
                                </asp:GridView>
                              <%--  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testdb1ConnectionString %>"
                                    SelectCommand="SELECT * FROM [tblAttachment]"></asp:SqlDataSource>--%>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>



Class Code : 


string connection = ConfigurationManager.ConnectionStrings["testdb1ConnectionString"].ConnectionString;
        SqlConnection conn;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindGridData();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection(connection);
            conn.Open();

            string path = FileUpload1.PostedFile.FileName.ToString();
            string FileName = FileUpload1.FileName.ToString();
            string FileSize = FileUpload1.PostedFile.ContentLength.ToString();
            string FileContent = FileUpload1.PostedFile.ContentType.ToString();
            string filename = Path.GetFileName(path);

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
            br.Close();
            fs.Close();


            string strQuery = "INSERT INTO [testdb1].[dbo].[tblAttachment]([f_name],[fileSize],[attachment],[contentType]) VALUES(@f_name,@fileSize,@attachment,@contentType)";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@f_name", SqlDbType.VarChar).Value = FileName;
            cmd.Parameters.Add("@fileSize", SqlDbType.VarChar).Value = Convert.ToInt32(FileSize);
            cmd.Parameters.Add("@attachment", SqlDbType.Binary).Value = bytes;
            cmd.Parameters.Add("@contentType", SqlDbType.VarChar).Value = FileContent;
            InsertUpdateData(cmd);
            bindGridData();

            conn.Close();
        }


        public void bindGridData()
        {
            conn = new SqlConnection(connection);
            conn.Open();
            string strquery = "select * from [testdb1].[dbo].[tblAttachment] ";
            DataTable dt = new DataTable();
            dt = getDataTable(strquery);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }



        private Boolean InsertUpdateData(SqlCommand cmd)
        {
            String strConnString = System.Configuration.ConfigurationManager
            .ConnectionStrings["testdb1ConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return false;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        protected void gvEmp_SelectedIndexChanged(object sender, EventArgs e)
        {
            int i = Convert.ToInt32(GridView1.SelectedRow.Cells[1].Text);

            conn = new SqlConnection(connection);
            conn.Open();

            string strquery = "select * from [testdb1].[dbo].[tblAttachment] where id='" + i + "' ";

            DataTable dt = new DataTable();

            dt = getDataTable(strquery);




            conn.Close();
        }


        protected void gvEmpSearch_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "name")
            {
                conn = new SqlConnection(connection);
                int index = Convert.ToInt32(e.CommandArgument);
                //GridViewRow selectedRow = GridView1.Rows[index];
                string EmpId = GridView1.DataKeys[index].Value.ToString().Trim();
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "select * from [testdb1].[dbo].[tblAttachment] where id=@id";
                cmd.Parameters.AddWithValue("@id", EmpId);
                cmd.Connection = conn;
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    Response.ContentType = dr["contentType"].ToString();
                    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["f_name"] + "\"");
                    Response.BinaryWrite((byte[])dr["attachment"]);
                    Response.End();
                }
                conn.Close();
            }
        }



        public DataTable getDataTable(string query)
        {
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            SqlCommand cmd1 = new SqlCommand(query, conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd1);
            DataTable dt = new DataTable();
            da.Fill(dt);
            conn.Close();
            return dt;

        }



Web.Config :

Write your connection string in web.config

Enjoy..... Happy Coding....





Comments

Popular posts from this blog

Add Serial no in crystal report without coding

File operations in C# (.net)

SQL – Generate decimal numbers sequence for particular number range