Friday, March 31, 2006

Sending a file to the client

Sometimes you need to send a file to the client by them clicking a link. If it is stored on your hard drive (appologies for the bad formatting. busy day today):

private sub SendFile(fileName as string)
dim filepath as string = Server.MapPath("files") & fileName

filepath = Server.UrlPathEncode(filepath) 'encoded to remove special characters i.e. spaces

response.clear() 'clear the output buffer

Response.ContentType = "application/binary" 'binaries are almost always downloaded. If it was set to excel for an excel file the browser might try to open it in the browser window

Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName) 'This is what tells the browser the filename to prompt the user with when they save it

Response.TransmitFile(filePath) 'transmit the file (internally reads and sends the file to the client

Response.Flush() 'write everything in the buffer to the client

Response.End() 'end the response so nothing else gets sent to the browser

end sub


Often you have these files in an area outside of the web root or in a database. If you have this scenario you can use a

Response.BinaryWrite(bytearray)

to send a bytearray to the client. You can easily get a byte array by reading a file with a filestream and then copying that to a byte array. Wish I had time to post on that today but sadly I do not.

0 Comments:

Post a Comment

<< Home