Monday, September 13, 2010

File Download in asp.net in 5 minutes

Hello friends,

It’s almost 2 week that I did not post any article friends sorry for that busy in some other high priority task. Today we will work on how to download a file with asp.net which exists in database.

So friends here we go.

Let us suppose we have a table of document in which we keep document in binary format. Suppose the table structure is as follows.
lngId
strFileName
strDescription
strContentType
binDocumentFile

Now what we have to do is by passing just lngId we will download the file or open in browser.
The code for doing this so simple.
Which I mention below

Dim sqlcon as New Sqlconnection(strConnectionString)
Sqlcon.open()
Dim ds as new dataset
Dim sqlcmd as new sqlcommand
Sqlcmd.connection =sqlcon
Sqlcmd.commandType = commandtype.storeprocedure
Sqlcmd.commandtext = “proc_getDocumentById”
Sqlcmd.parameters.add(“@lngId”,intDocumentId) ‘int documented is lngID of document
Dim sda as new sqldataAdapter
Sda.selectCommand = sqlcmd
Sda.fill(ds)

If ds Is Nothing = False AndAlso ds.tables(0).rows.count >0 Then
Dim dr As dataRow = ds.tables(0).Rows(0)
Context.Response.Clear()
Context.Response.ContentType = dr (“DOCTYPE”).ToString()
Dim intLength As Integer = DirectCast(dr (“DOCDATA”), Byte()).Length()
Context.Response.AddHeader(“Content-Disposition”, “inline;filename=” & dr (“DOCNAME”))
‘ Context.Response.AddHeader(“Content-Disposition”, “attachment;filename=” & dr (“DOCNAME”))
Context.Response.AddHeader(“content-length”, intLength)
Context.Response.AddHeader(“Pragma”, “public”)
Context.Response.AddHeader(“Cache-Control”, “public”)
Context.Response.CacheControl = “public”
Context.Response.BinaryWrite(DirectCast(dr(“DOCDATA”), Byte()))
Context.Response.End()
dR = nothing
end If
Ds = nothing
Sqlcmd = nothing
Sqlcon = nothing
Sda = nothing

Now the main important point here is content – disposition, and content type
Content type is basically type of content which we are going to download like, JPEG, word, text, etc
And content disposition describe that whether you want download the file or open in browser.
If you want to open in browser then use “inline” and if you want to download then use “attachment” in disposition setting.

So in this way we easily download and kind of file.
If you feel any kind of suggestion, discussions feel free to contact.

Thanks & Esteemed Regards
Rajat Jaiswal
Samsung Epic 4G Android Phone (Sprint)