Forcing downloading files by save dialog

Here is the code snippet for downloading files with asp.net:

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpeg";

byte[] data = System.IO.File.ReadAllBytes(MapPath(url));
Response.BinaryWrite(data);
Response.Flush();
Response.End();


The key moment in forced save dialog is the header "content-disposition" with file attachment. This will tell to your browser to show you dialog and give you the possibility to get directly that file.
If you use attachment in "inline" header (appending it instead of "content-disposition") the file is gonna be opened in the same window. Browser back button can get you back on your page.

List of content types can be found here: MIME Reference

No comments:

Post a Comment