Tuesday 14 May 2013

Widgets

Upload and Download Files From Database in Asp.Net

Demo:-
   

Click On Image To Enlarge

Instruction:- To use this code first you create a table in Sql Server named as file_table.And make these fields in Table Given Below in Picture.



Design Code:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<title>Upload Word Document Files
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btn_Upload" />
</div>
<div>
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" DataKeyNames="Id">
<HeaderStyle BackColor="blue" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="Download_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Code Behind:-

using System;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    string strCon = "Data Source=IT-HP\\sqlexpress;Initial Catalog=Employee;Integrated Security=True";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridviewData();
        }
    }
    // Bind Gridview Data
    private void BindGridviewData()
    {
        using (SqlConnection con=new SqlConnection(strCon))
        {
            using (SqlCommand cmd=new SqlCommand())
            {
                cmd.CommandText = "select * from File_Table";
                cmd.Connection = con;
                con.Open();
                gvDetails.DataSource = cmd.ExecuteReader();
                gvDetails.DataBind();
                con.Close();
            }
        }
     }
    // Save files to Folder and files path in database
    protected void btn_Upload(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
        Stream str = fileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(str);
        Byte[] size = br.ReadBytes((int) str.Length);
        using (SqlConnection con=new SqlConnection(strCon))
        {
            using (SqlCommand cmd=new SqlCommand())
            {
                cmd.CommandText = "insert into File_Table(FileName,FileType,FileData) values(@Name,@Type,@Data)";
                cmd.Parameters.AddWithValue("@Name", filename);
                cmd.Parameters.AddWithValue("@Type", "application/word");
                cmd.Parameters.AddWithValue("@Data", size);
                cmd.Connection =con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                BindGridviewData();  
            }
        }
    }
    // This button click event is used to download files from gridview
    protected void Download_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        int fileid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value.ToString());
        string name, type;
        using (SqlConnection con=new SqlConnection(strCon))
        {
            using (SqlCommand cmd=new SqlCommand())
            {
                cmd.CommandText = "select FileName, FileType, FileData from File_Table where Id=@Id";
                cmd.Parameters.AddWithValue("@id", fileid);
                cmd.Connection = con;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if(dr.Read())
                {
                    Response.ContentType = dr["FileType"].ToString();
                    Response.AddHeader("Content-Disposition", "attachment;filename=\"" +dr["FileName"] + "\"");
                    Response.BinaryWrite((byte[])dr["FileData"]);
                    Response.End();
                }
            }
        }
    }
}






0 comments:

Post a Comment