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

Host your site with me in free

Hello friends Here are some free hosting services which I prefer to use. I would like to share this with you so that you will also create your account on this and use free services of hosting from this hosting units.

1) Web Host for Asp :-

 

 2) Brinskter :-

 

3) 7 Host:-

 

Other than this there are some other services which provide free asp.net hosting like aspspider.net. So enjoy your work with this.
Thanks &
regards
Rajat Jaiswal