Hi suhaas121,
I have created a sample please take its refrence and correct your code.
Database
This article makes use of a table named tblFiles whose schema is defined as follows.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
ID:<asp:TextBox runat="server" ID="txtID" />
<asp:Button ID="btndownload" runat="server" Text="Download" OnClick="btndownload_Click"
Style="font-weight: bold;" OnClientClick="this.disabled = true;" UseSubmitBehavior="false" />
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void btndownload_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
try
{
byte[] bytes;
btndownload.Enabled = false;
string filename, contentType;
SqlCommand cmd1 = new SqlCommand("SELECT Name, Data, ContentType FROM TblFiles WHERE ID=@ID", conn);
cmd1.Parameters.AddWithValue("@ID", txtID.Text.Trim());
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
btndownload.Enabled = false;
bytes = (byte[])dr["Data"];
contentType = dr["ContentType"].ToString();
filename = dr["Name"].ToString();
conn.Close();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End;
}
}
catch (Exception ex)
{
}
}
VB.Net
Protected Sub btndownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
Try
Dim bytes As Byte()
btndownload.Enabled = False
Dim filename, contentType As String
Dim cmd1 As SqlCommand = New SqlCommand("SELECT Name, Data, ContentType FROM TblFiles WHERE ID=@ID", conn)
cmd1.Parameters.AddWithValue("@ID", txtID.Text.Trim())
conn.Open()
Dim dr As SqlDataReader = cmd1.ExecuteReader()
If dr.Read() Then
btndownload.Enabled = False
bytes = CType(dr("Data"), Byte())
contentType = dr("ContentType").ToString()
filename = dr("Name").ToString()
conn.Close()
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename)
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
Catch ex As Exception
End Try
End Sub
Screenshot