HTTP Response Header 之 Content-Disposition

When you serve a document from a Web server, you might want to immediately prompt the user to save the file directly to the user's disk, without opening it in the browser. However, for known MIME (Multipurpose Internet Mail Extensions) types such as Microsoft Word ("application/ms-word"), the default behavior is to open the document in Internet Explorer.
You can use the content-disposition header to override this default behavior. Its format is:

Content-disposition: attachment; filename=fname.ext
				

Content-disposition is an extension to the MIME protocol that instructs a MIME user agent on how it should display an attached file. The range of valid values for content-disposition are discussed in Request for Comment (RFC) 1806 (see the "References" section of this article). This article focuses on the "attachment" argument, which instructs a user agent (in this case, Internet Explorer) to save a file to disk instead of saving it inline.
When Internet Explorer receives the header, it raises a File Download dialog box whose file name box is automatically populated with the file name that is specified in the header. (Note that this is by design; there is no way to use this feature to save a document to the user's computer without prompting him or her for a save location.)

另:

在进行 Web 开发时,可能遇到遇到以下几种需求:

  • 希望某类或者某已知 MIME 类型的文件(比如:*.gif;*.txt;*.htm)能够在访问时弹出“文件下载”对话框。
  • 希望客户端下载时以指定文件名显示。
  • 希望某文件直接在浏览器上显示而不是弹出文件下载对话框。

对于上面的需求,使用 Content-Disposition 属性就可以解决。下面是代码示例:

response.setHeader("Content-disposition", "attachment;filename=" + fileName)

  • Content-disposition 为属性名。
  • attachment 表示以附件方式下载。如果要在页面中打开,则改为 inline。
  • filename 如果为中文,则会出现乱码。解决办法有两种:
    • 使用 fileName = new String(fileName.getBytes(), "ISO8859-1") 语句
    • 使用 fileName = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) 语句
posted @ 2010-08-31 20:18  Comm100 Testers  阅读(3178)  评论(0编辑  收藏  举报