Following an article on how to do this using ASP 3.0, we’ll see how to accomplish the same effect using ASP.NET. Using streams, we can provide a file to the user without the need for FTP or any interference of the Internet Information Server (IIS).
Create an ASPX file, called download.aspx. This file takes a filename as a parameter, and returns the contents of that file in the response stream. For example, if you wanted to have the users download a file called logo.gif residing in the images folder, you would do so like this:
The complete code in VB.NET:
First, we check to see if something was passed in the QueryString, and if nothing was, then we output an error. Then we run our code only if the file actually exists on the web server. All the conditional statements are there to avoid errors in our output. Two headers are needed: one for telling the browser to save the stream as an attachment, and the other to set the length of the stream so that the browser will properly display a download progress bar. The main method here is the WriteFile, which writes the contents of the file in the response stream.
The ContentType header which is added, sets your MIME type so that the browser knows what kind of file this is. You can see a listing of all the MIME types supported on your server, by looking in your web server’s properties under MIME types. For example, if you are serving an MS Word file, this would be “application/msword“. Octet-stream, which is used above, is a straight binary and acts as a catch-all datatype: when you define something with this datatype, the web server will simply let you download or open the file.
This code should work for all files on Windows systems, but there are some issues with Macintosh systems. Specifically, you may not be able to download the files, instead they will always open up in the browser as expected.