zoukankan      html  css  js  c++  java
  • HTTP Response Header 之 ContentDisposition

    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) 语句
  • 相关阅读:
    第三方网站实现绑定微信登陆
    安卓微信中bootstrap下拉菜单无法正常工作的解决方案
    一个Web钢琴谱记忆工具
    腾讯实习生面试经历-15年3月-Web前端岗
    AngularJS自定义指令三种scope
    AngularJS在自定义指令中传递Model
    Canvas文本绘制的浏览器差异
    AngularJS学习笔记
    善用width:auto以及white-space:nowrap以防止布局被打破
    Timeline中frame mode帧模式中idle占据大片位置
  • 原文地址:https://www.cnblogs.com/henryhappier/p/1814005.html
Copyright © 2011-2022 走看看