Pages

Wednesday 24 April 2013

How to Upload Files to Database in Asp.net Download Files From Database in SQL Server

How to Upload Files to Database in Asp.net Download Files From Database in SQL Server

Program:

.Aspx File


<%@ 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 Files to Database and Download files from database in asp.net
</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="btnUpload_Click" />
</div>
<div>
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" DataKeyNames="Id">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

.Aspx.cs File

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=SURANI-PC\\SA;Initial Catalog=demo;Integrated Security=True";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridviewData();
        }
    }
    private void BindGridviewData()
    {
        using (SqlConnection con=new SqlConnection(strCon))
        {
            using (SqlCommand cmd=new SqlCommand())
            {
                cmd.CommandText = "select * from FileInformation";
                cmd.Connection = con;
                con.Open();
                gvDetails.DataSource = cmd.ExecuteReader();
                gvDetails.DataBind();
                con.Close();
            }
        }
     }
    // Save files to Folder and files path in database
    protected void btnUpload_Click(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 FileInformation(Name,Type,data) 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();  
            }
        }
    }
    protected void lnkDownload_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());
        using (SqlConnection con=new SqlConnection(strCon))
        {
            using (SqlCommand cmd=new SqlCommand())
            {
                cmd.CommandText = "select Name, Type, data from FileInformation where Id=@Id";
                cmd.Parameters.AddWithValue("@id", fileid);
                cmd.Connection = con;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if(dr.Read())
                {
                    Response.ContentType = dr["Type"].ToString();
                    Response.AddHeader("Content-Disposition", "attachment;filename=\"" +dr["Name"] + "\"");
                    Response.BinaryWrite((byte[])dr["data"]);
                    Response.End();
                }
            }
        }
    }
}

VB File

Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls
Partial Class VBCode
    Inherits System.Web.UI.Page
    Private strCon As String = "Data Source=SURANI-PC\SA;Initial Catalog=demo;Integrated Security=True"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGridviewData()
        End If
    End Sub
    Private Sub BindGridviewData()
        Using con As New SqlConnection(strCon)
            Using cmd As New SqlCommand()
                cmd.CommandText = "select * from FileInformation"
                cmd.Connection = con
                con.Open()
                gvDetails.DataSource = cmd.ExecuteReader()
                gvDetails.DataBind()
                con.Close()
            End Using
        End Using
    End Sub
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
        Dim str As Stream = fileUpload1.PostedFile.InputStream
        Dim br As New BinaryReader(str)
        Dim size As [Byte]() = br.ReadBytes(CInt(str.Length))
        Using con As New SqlConnection(strCon)
            Using cmd As New SqlCommand()
                cmd.CommandText = "insert into FileInformation(Name,Type,Data) 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()
            End Using
        End Using
    End Sub
    Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
        Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
        Dim fileid As Integer = Convert.ToInt32(gvDetails.DataKeys(gvrow.RowIndex).Value.ToString())
        Using con As New SqlConnection(strCon)
            Using cmd As New SqlCommand()
                cmd.CommandText = "select Name, Type, data from FileInformation where Id=@Id"
                cmd.Parameters.AddWithValue("@id", fileid)
                cmd.Connection = con
                con.Open()
                Dim dr As SqlDataReader = cmd.ExecuteReader()
                If dr.Read() Then
                    Response.ContentType = dr("Type").ToString()
                    Response.AddHeader("Content-Disposition", "attachment;filename=""" & Convert.ToString(dr("Name")) & """")
                    Response.BinaryWrite(DirectCast(dr("data"), Byte()))
                    Response.[End]()
                End If
            End Using
        End Using
    End Sub
End Class

Demo:


How to Upload Files to Database in Asp.net Download Files From Database in SQL Server
How to Upload Files to Database in Asp.net Download Files From Database in SQL Server

No comments:

Post a Comment