Wednesday, August 10, 2011

Sending a dynamic file to the client in ASP.Net

Sending a dynamic file (a file you either generate on the fly or have stored in the database) to the client in ASP.Net is fairly simple, but there are a few details to take into consideration if you want optimal results.

First, I would recommend avoiding sending files from a page with another purpose. If you send files or do redirects within an ASP.Net control event it can make your user's browser navigation buttons difficult to use. For example, if the user downloads the file then navigates to the next page then hits the back button, her browser will download the file a second time. To make the user's life as convenient as possible you will want to create dedicated download page.

Create a new Web Form (without a Master Page) and delete everything except the @ Page tag on the first line. Next, add the following attribute to your Page tag: Theme=""
The empty value will prevent your page from attempting to load a theme.

You will now want to go to the codebehind and add a Page_PreInit method; this is the best place to put your file download logic since you will not have to waste time parsing the markup. Before you add the following logic, do not forget to do your security checks if your files are not always publicly accessible.





Response.ClearContent();

This will clear any html generated in the request; it is probably not necessary if you followed all the above steps, however.

Response.ClearHeaders();

This will clear the HTTP headers.

Response.BinaryWrite(YourFileData);

Write the contents of the file to the response in the form of a byte array.

Response.ContentType = "application/octet-stream";

This tells the browser that it is dealing with a file as opposed to html. This generic MIME type should work for everything, but if you want to get more specific you can match the MIME type to your file here.

Response.AddHeader("Content-Disposition", "attachment; filename=" + YourFileName);

The content disposition is important for making the browser treat this as a normal file so it will not display as "FileDownload.aspx"

Response.AddHeader("Content-Length", YourFileSize.ToString());

This lets the involved parties know how large the file is; dot your "I"s and cross your "T"s

Response.End();

Finally, send the file to the client.



If you followed all the above steps, your client should have their file and have no idea that is was served dynamically. Happy coding!




No comments:

Post a Comment