控制下载文件的名字   Leave a comment

//tell browser program going to return an application file
//instead of html page
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=temp.csv");
temp.csv可以改为任何的其他文件名

Content-Disposition header - forcing SaveAs in browsers

There are situations (to save a documentation in pdf format or a financial document) where you might want a hyperlink leading to a file to present a SaveAs dialog in browser. Ways to do that exist. However, flaky browser support makes its usage a walk in the mine field.

Forcing SaveAs using javascript in Internet Explorer

By means of javascript you can provide a dialog to save the page that is currently displayed (if the user is looking through Internet Explorer at your page that is).  For example:  Save this page This is done through the following code: <a href="javascript:void(0);" onclick="document.execCommand('SaveAs',true,'file.html');" >Save this page</a> However, usually you want to save another file, the file a hyperlink leads to. To do that javascript is not enough (at least there is no such standard way) and something must be done on the server.

Forcing SaveAs using the HTTP header

In order to force the browser to show SaveAs dialog when clicking a hyperlink you have to include the following header in HTTP response of the file to be downloaded:  Content-Disposition: attachment; filename=<file name.ext>  Where <file name.ext> is the filename you want to appear in SaveAs dialog (like finances.xls or mortgage.pdf) - without < and > symbols.  You have to keep the following in mind:
  • The filename should be in US-ASCII charset.
  • The filename should not have any directory path information specified.
  • The filename should not be enclosed in double quotes even though most browsers will support it.
  • Content-Type header should be before Content-Disposition.
  • Content-Type header should refer to an unknown MIME type (at least until the older browsers go away).

Posted 2011年03月2日 by gw8310 in 未分类

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: