Monday, December 13, 2010

How to force a file to download in ASP.NET ?

How the Code Works

There are lots of file type which can be handled by IE (or other browsers Firefox, Opera etc.) like HTML, XML, JPEG, GIF, SWF, PDF, DOC etc. In case the browser can not handle the a particular file type it will ask you to open or save that file. Sometime you may want to force the user to download a particular file even though browser can open that file type because of any of your business need. This can be easily achieved by adding the content-disposition header in the response of your page.

Take below example. Here we are writing a gif file in response and forcing the user to download this file.

 
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=logo_large.gif");
Response.ContentType = "image/GIF";
Response.WriteFile(Server.MapPath(@"~/logo_large.gif"));
Response.End();
}

No comments :

Post a Comment