Header Ads

Download a file from database

Hi , we have to discuss about how to download a file from the database , we generally upload a file to database in binary form so how to download that file that is going to see here..

suppose if i upload a file and bind the file detail in Gridview or datalist there i have give the Download link - here i am passing the id of the specific row so using this is i will retrieve the file.
so we pass the id to other page to make the file as download.

If Not Request.QueryString("id") Is Nothing Then
Dim As New SqlCommand("Select * from where download_id like @id", con)
Dim ID As New SqlParameter("@ID", SqlDbType.SmallInt, 2)
ID.Value = Request.QueryString("id")
ID.Direction = ParameterDirection.Input
cmd.Parameters.Add(ID)
cmd.Connection = con
con.Open()
Dim dRE As SqlDataReader
dRE = cmd.ExecuteReader()
While dRE.Read()
Dim myTitle As String = dRE.GetString(4).ToString 'document title
Dim myType As String = dRE.GetValue(5).ToString 'document type
If myTitle = "None" Or myType = "None" Then
message.Text = "No Attachements Present !"
Exit Sub
Else
Dim myDoc = dRE.GetSqlBinary(3) 'document


Response.Buffer = True
Response.Clear()
Response.AddHeader("content-disposition", "attachment; filename=" & myTitle)
'application/octet-stream
Select Case myType.ToLower
Case "doc"
Response.ContentType = "application/msword"
Case "docx"
Response.ContentType = "application/msword"
Case "ppt"
Response.ContentType = "application/vnd.ms-powerpoint"
Case "xls"
Response.ContentType = "application/x-msexcel"
Case "htm"
Response.ContentType = "text/HTML"
Case "html"
Response.ContentType = "text/HTML"
Case "jpg"
Response.ContentType = "image/JPEG"
Case "gif"
Response.ContentType = "image/GIF"
Case "pdf"
Response.ContentType = "application/pdf"
Case Else
Response.ContentType = "text/plain"
End Select
Response.BinaryWrite(myDoc.Value)
Response.Flush()
Response.Close()
If myDoc.isNull Then
message.Text &= "Retrieving File: " _
& myTitle & "." & myType & " Size: NULL
"
Else
message.Text &= "Retrieving File: " _
& myTitle & "." & myType & " Size: " & myDoc.ToString() & "
"
End If
End If
End While
con.Dispose()
con = Nothing
cmdDownloadDoc.Dispose()
cmdDownloadDoc = Nothing

End If
End Sub

No comments:



Powered by Blogger.