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) 语句
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值