yinix

_Asp.net_Ajax
posts - 13, comments - 4, trackbacks - 0, articles - 29

导航

英文文章:
http://west-wind.com/WebLog/posts/76293.aspx

This seems to be a common question that I hear frequently: How do I 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)?

Normally when you link a file that file will always display inside of the browser because the browser loads it and automatically determines the content type based on the file extension. So when you click on a link like a jpg image the browser knows it's an image and will display that image. You can of course always use the browser short cut menu and use the Save Target As option to save the file to disk.

If you want to do this automatically when a link is clicked from the server side, you have to send the file back yourself rather and add a couple of custom headers to the output. The way to do this is to use Response.TransmitFile() to explicitly send the file from your ASP.NET application and then add the Content Type and Content-Disposition headers.

For example:


Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");
Response.TransmitFile( Server.MapPath("~/images/sailbig.jpg") );
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.

This of course assumes you're feeding a file that already exists. If you need to feed dynamically generated - say an image that was generated in memory - you can use Response.BinaryWrite() to stream a byte array or write the output directly in Response.OutputStream.

Bitmap bmp = wwWebUtils.CornerImage(backcolor, color, c, Radius, Height, Width);

 

Response.ContentType = "image/jpeg";

Response.AppendHeader("Content-Disposition","attachment; filename=LeftCorner.jpg");

 

bmp.Save(Response.OutputStream, ImageFormat.Jpeg);

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). 


中文文章:http://www.cnblogs.com/dflying/archive/2007/06/01/768251.html

 

这个主题不知道已经被多少人问过多少遍了,无论是ASP.NET,还是PHP还是什么别的CGI,似乎这也算做一个“永恒”的话题了。

其实解决方案很简单(无论哪个CGI平台都是如此),只是一个header而已:

Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");
Response.TransmitFile( Server.MapPath("~/images/sailbig.jpg") );
Response.End();