Mark Mintoff My superpower is common sense


ASP.Net File Serving

The best way to go about creating downloadable files in ASP.Net is to control the way in which those files are served to the users. Some of the most apparently obvious advantages are:

  • Controlling the response header, allowing for a forced download
  • Hiding the directory structure of your website
  • Easy way to control file access through rights
  • File download tracking

To do this, we need to create a Generic Handler (.ashx) in our project.I added one and named it "File.ashx".

Working with generic handlers is super easy. All it takes is programming; no design. Most systems utilize a database to track files and I will be working on this assumption.

In the ProcessRequest method, we will first do some querystring handling to get the ID of the file:

Here, we are simply acquiring the file of the ID and ensuring that the application will not crash through querystring manipulation.

I did not want to get into the details of database implementation, so I wrote the following code block as a simulation of fetching from the database:

I am making the assumption here that the MIME type is already stored in the database along with other information about the file. The best time to extract the MIME type from the file would be during the upload to the server. In order to do this, I developed my own (long...224 lines) method to extract the MIME type from an HttpPostedFile object.

Moving on however, after we have the file name and mime type information, it is time to actually serve the file. We can do this by writing the file into the Response's Output Stream, but first we need to read the file into a byte array.

The byte array returned from this method will then be written into the OutputStream, along with some other information. One of the things we should do is control whether or not the file is a download; forcing the browser to download the file onto the computer as opposed to handling the file how it sees fit. For example, many browsers handle images by opening the image in the browser itself which may not be a desired outcome. Alternatively there may be some files that the browser does not know how to handle (docx for example) and will instead opt to do nothing rather than download the file. Hence:

Here, we are writing the file into the Output Stream, specifying the content type (MIME Type) and setting the content-disposition, determining whether or not the file is a download. It is necessary to wrap the file name in quotes because Firefox does not handle file names with spaces otherwise.

Finally, the way to access the file (from the downloadable example) is creating a link as follows:

And here is the obligatory, downloadable example:

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)