In this article, we will see how to allow users to download any file from a web server by streaming it through ASP. They will see a prompt, giving them the option of opening or saving it, rather than simply opening it which is the default. We can achieve this using the FSO and ADODB objects.
The desired effect
There are times when you want users to download a file instead of opening it up in a browser; like images, text files, ASP code files, MS Office files like Powerpoint or Word files, etc. That’s easy to do for a ZIP file for example, but hard with a GIF or TXT. The reason is that anything that the browser recognizes as a valid format, it will open right away without giving you the option to save it. We want the user to receive a prompt though, asking them if they want to save or open the file, like below:
We can achieve the above for any file, by simply editing the Response that the browser receives from our web server. By editing the header and the content type, we can prepare the browser to accept binary streams, which would then save as attachments. So, it will always prompt the users to save the content.
<%@Language="VBScript"%> <%Option Explicit%> <%Response.Buffer = True%> <% On Error Resume Next Dim strPath strPath = CStr(Request.QueryString("file")) '-- do some basic error checking for the QueryString If strPath = "" Then Response.Clear Response.Write("No file specified.") Response.End ElseIf InStr(strPath, "..") > 0 Then Response.Clear Response.Write("Illegal folder location.") Response.End ElseIf Len(strPath) > 1024 Then Response.Clear Response.Write("Folder path too long.") Response.End Else Call DownloadFile(strPath) End If Private Sub DownloadFile(file) '--declare variables Dim strAbsFile Dim strFileExtension Dim objFSO Dim objFile Dim objStream '-- set absolute file location strAbsFile = Server.MapPath(file) '-- create FSO object to check if file exists and get properties Set objFSO = Server.CreateObject("Scripting.FileSystemObject") '-- check to see if the file exists If objFSO.FileExists(strAbsFile) Then Set objFile = objFSO.GetFile(strAbsFile) '-- first clear the response, and then set the appropriate headers Response.Clear '-- the filename you give it will be the one that is shown ' to the users by default when they save Response.AddHeader "Content-Disposition", "attachment; filename=" & objFile.Name Response.AddHeader "Content-Length", objFile.Size Response.ContentType = "application/octet-stream" Set objStream = Server.CreateObject("ADODB.Stream") objStream.Open '-- set as binary objStream.Type = 1 Response.CharSet = "UTF-8" '-- load into the stream the file objStream.LoadFromFile(strAbsFile) '-- send the stream in the response Response.BinaryWrite(objStream.Read) objStream.Close Set objStream = Nothing Set objFile = Nothing Else 'objFSO.FileExists(strAbsFile) Response.Clear Response.Write("No such file exists.") End If Set objFSO = Nothing End Sub %>