netnerds.net

22Jan/0723

Classic ASP: "Push" File Downloads from A Directory Outside the Application Root

This is some super old code but I used it recently and figured I'd archive it on this site for my future reference. The sample code below aims to allow authenticated users to download files which are not available via direct download (ie. files within the web root). The script accomplishes this by doing the following:

1. Checks to see if the user is logged in (your method may vary)
2. Sets the root directory location
3. Checks to see if the file exists, if so...
4. Retrieves the filesize and adds the appropriate HTTP headers including content disposition, filename, content type and filesize.
5. Uses a binary stream to "push" the download

Save this file as download.asp and call it with the filename in the querystring. Example: http://domain.com/downloads/download.asp?filename=myfile.pdf. Also, be sure to give read permissions to IUSR_SvrName to the root directory. Change the authentication requirements as needed:

download.asp

<%
If session("loggedIn") = True Then

strFilePath = "D:\webfiles\downloads"  & request.querystring("filename")

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strFilePath) Then
Set objFile = objFSO.GetFile(strFilePath)
intFileSize = objFile.Size
Set objFile = Nothing

strFileName = request.querystring("filename")
strFileName = replace(request.querystring("filename")," ","-")
Response.AddHeader "Content-Disposition","attachment; filename=" & strFileName

Response.ContentType = "application/x-msdownload"
Response.AddHeader "Content-Length", intFileSize

Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = 1 'adTypeBinary
objStream.LoadFromFile strFilePath
Do While Not objStream.EOS And Response.IsClientConnected
Response.BinaryWrite objStream.Read(1024)
Response.Flush()
Loop
objStream.Close
Set objStream = Nothing
Else
Response.write "Error finding file."
End if
Set objFSO = Nothing
End If
%>

Note: Even if the file is a PDF and a third-party application such as Adobe Reader is set to open the file within the browser, the code below will override that and force a download (by using the "application/x-msdownload" content type).

[The UPDATE below is no longer accurate as an alternative solution has been given below in the comments and subsequently, was added to the code (Thanks a bunch, David!). I wanted to leave it for Googlers looking for a solution, however]

UPDATE: Someone wrote to let me know that they were encountering the error "Response Buffer Limit Exceeded". As it turns out, IIS 6's ASPBufferingLimit is set to a measly 4MB (4194304 bits) so any file over 4MB would produce this error. To fix this issue, you will have to have access to IIS either via the command line or the MMC. Here's how to change the buffering limit via the command line:

************ NOTE: An easier solution is to use the updated Do While/Flush procedure given in the code *****************

cd C:\inetpub\adminscripts
cscript adsutil.vbs set /w3svc/aspbufferinglimit 4294967295

That's a buffering limit of more than 4 Gigabytes. Personally, I'd lop off the last digit and make that number closer to 430MB. Running that script worked immediately on my test machine, even though I do not have "Enable Direct Metabase Edit" checked in IIS' Properties. If it doesn't work for you, restart IIS and see if it works.

Posted by: Chrissy   Filed under: IIS, VBScript Leave a comment
Comments (23) Trackbacks (0)
  1. Hai Dude,

    That was a good example..Easy to understand.. Nice presentation.. This is the first time i do mail to a persons article..Keep up your good work.. All these stuff will help us to get projects done in correct time and will give a rescue from our senior people :) LOL !!!!!!

    Anyway thanks a lot..

    Bye

  2. Good article and code. Do you know if your going to use mp3 files how I can get it so it saves as a mp3? Right now with your code it just saves the file as the name of the script (file.asp). It would be nice to save as songname.mp3. Anythoughts?

  3. Hey Lee,
    You are right..sorry about that, I did a mass replace and replaced one too many variables. The following line

    “Content-Disposition”,”attachment; strFileName=” & strFileName

    should read
    “Content-Disposition”,”attachment; filename=” & strFileName

    I will update the code.

    Chrissy

  4. Thanks for the example. This really helped me move along with a project. I was able to get around the buffering limit simply by reading and writing in chunks which should probably be done anyway. Instead of the one BinaryWrite call, replace with the following:

    Do While Not objStream.EOS And Response.IsClientConnected
    Response.BinaryWrite objStream.Read(1024)
    Response.Flush()
    Loop

    I no longer receive the buffering limit message.

  5. David,
    EXCELLENT Solution! Thanks so much!

  6. Been looking for something like this for past 2 days.

    Threw it on my Dev site, changed it a bit, and works like a charm.

    Thanks :D

  7. Generally, google is as useful as a one-legged man in an arse-kicking competition for finding info like this quickly but today i’ve hit the jackpot. Thanks a million dude!

  8. I agree with everybody else, I could not find this anywhere on google and this was the answer to all my questions. Thanks a million!

  9. Fighting with this for past one month and getting refused by the hosting company to changes its IIS 6′s ASPBufferingLimit for me, i thought my application’s life is over, until today. Thanks a Trillion!

  10. Is there any way for me to trigger the download dialog box from a remote file store? My .mp3 file is hosted at Amazon S3 and is accessed using a URL.

    I have the .mp3 files local but don’t want to deal with the bandwidth issues when the site becomes popular.

    Or, how about using HTML or Javascript instead of ASP?

  11. Excellent! Thank you so much for posting this!

  12. This is awesome! Worked like a charm with the user authentication I already had setup. Thanks for posting and making updates!

  13. WOW! This little piece of code just made my day. I had been looking for something to do this for a while.

    Thanks m8

  14. Is there a way to show a progress bar for really large files? It seems to work but a 200-300mb file will churn for quite some time without screen feedback

  15. Thank you very much Chrissy. This is exactly what I was looking for.

  16. Wow thank you so much, I have been pulling my hair out trying to find a way to DL larger files and still hide the dir, thanks so much!!

  17. Thank you, thank you and THANK YOU!!
    I’ve been trying to do this for weeks with no success and I finally found your code!
    It works perfectly!!! =)
    I just changed the first line to adjust to my login methods.

    =D

  18. Thx
    very much for this code,

  19. Like many of the preceding comments, this snippet of code was exactly what the doctor ordered.

    Like yourself, had an ancient site that required a solution just like yours.

    Cheers – David

  20. how to download file at root direcory without asking save as option in asp.net

  21. I have used your code and when i download i am getting an erro like this in chrome.I am new to this asp classic.

    If i upload a file of samller size i am able to download but if it is little big also i am facing this problem, what should i do now.

    The webpage at http://www.indiaroot.com/news/download.asp?File=%... might be temporarily down or it may have moved permanently to a new web address.
    Error 346 (net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH): Unknown error.

  22. THANKS A LOT FOR THIS CODE!!!

  23. Doing something like

    filePath = “D:\WebFiles\Downloads\” & Request.QueryString(“name”)

    and then using it directly is awful, it will allow anybody to download any file on the whole web server, as a user can pass something like ..\database_connection_strings.asp and download the source code of the page (or even more sensitive files).


Leave a comment


No trackbacks yet.