Guest Author - Christopher Combs
Have you ever been frustrated when you get to a website and there is documents, images and other content available for download and you want to do just that, download it! Instead, when you click on a content item, it proceeds to open in your browser. I was up against this issue during a project for a medical company and they needed their PDF files to be downloaded and not opened. Well, there is a way to make it open the Save As dialog box.
For this tutorial, we will assume the files are stored locally on the server and not in a database. (That is a whole different discussion)
First, you need to know the location of your files. So letís assume your files are located at http://yourserver.com/files/filename.ext. We will assume that the Server.MapPath is "/files".
So, at this point, letís create the ASP file that will control the downloading of the file. Start by creating a new, blank, document using NotePad or your favorite HTML editor. Place the following ASP code:
'Define the names of your functions
Const adTypeBinary = 1
'Get the actual file name from the URL that is passed to the browser
FileName = request.querystring("filename") 'Get the name from the URL
'GIVE AN ERROR MESSAGE IF THE URL IS EMPTY
if FileName = "" Then
response.write "Filename Not specified."
'prevent access to certain files
FileExt = Mid(FileName, InStrRev(FileName, ".") + 1)
select case UCase(FileExt)
Case "ASP", "ASA", "ASPX", "ASAX", "MDB"
response.write "You cannot access these file types."
'Start the download process if all is good
response.contentType = "application/octet-stream"
response.addheader "content-disposition", "attachment; filename=" & FileName
set stream = server.CreateObject("ADODB.Stream")
stream.type = adTypeBinary
stream.LoadFromFile Server.MapPath("/files") & FileName
while not stream.EOS
response.BinaryWrite Stream.Read(1024 * 64)
Set stream = Nothing
That is it for that one. Now, save and upload this file to your server and name it filedownloader.asp
Now letís say the filename on your server is familytree.pdf
Then you would simply pass the following URL in your browser and the File Save as Open dialog will pop up.
That is it! You should then see this:
Good luck and you can enhance this by using databases and other cool functions to make sure that the files you want your users to access are given the ability to be downloaded and not opened in their current web browser allowing them to "stay" on your website.