Tuesday, July 16, 2013

Downloading a File with a Save As Dialog in ASP.NET

How to download a file from a Web site, but instead of displaying it in the browser see it as a file that can be saved (ie. see the Save As dialog)?

string fileName = "logo.png";
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath("~/images/" + fileName));
Response.End();

This will cause a Open / Save As dialog box to pop up with the filename of SailBig.jpg as the default filename preset.


If at all possible though, use TransmitFile though especially if you plan on serving a file more than once. TransmitFile is very efficient because it basically offloads the file streaming to IIS including potentially causing the file to get cached in the Kernal cache (based on IIS's caching rules).

No comments:

Post a Comment