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:
<a href="download.aspx?file=/images/logo.gif">Download the logo image</a>
The complete code in VB.NET:
<%@ Page language="vb" runat="server" explicit="true" strict="true" %> <script language="vb" runat="server"> Sub Page_Load(Sender As Object, E As EventArgs) Dim strRequest As String = Request.QueryString("file") '-- if something was passed to the file querystring If strRequest <> "" Then 'get absolute path of the file Dim path As String = Server.MapPath(strRequest) 'get file object as FileInfo Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) '-- if the file exists on the server If file.Exists Then 'set appropriate headers Response.Clear() Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name) Response.AddHeader("Content-Length", file.Length.ToString()) Response.ContentType = "application/octet-stream" Response.WriteFile(file.FullName) Response.End 'if file does not exist Else Response.Write("This file does not exist.") End If 'nothing in the URL as HTTP GET Else Response.Write("Please provide a file to download.") End If End Sub </script>
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.