4

Let me start by saying that I am aware that you can specify the Content-Disposition in the header and use either "attachment" or "inline" and this question is NOT about that (at least not directly).

I have a file with a .txt extension. I am noticing different browser behavior dependent on the content of that .txt file. If my file contains alphanumeric characters and I paste the location of the file into the URL bar of (say) Chrome, the file opens in the browser.

If my file contains an "SI" character the file is downloaded instead of opened in the browser.

At first I thought it might be because "SI" is a control code, but "CR" and "LF" are also control codes and the file displays in the browser when they are present. The file even opens in the Chrome when there is a "DC2" character present in the .txt file.

My question is: At the file content level, what determines whether or not a file is displayed or downloaded?

(I realize this may vary by browser, but if there is something that's at least somewhat reliable, it would be helpful to know)

Thanks in advance.

EDIT (based on answer from Sam):

When the "SI" or "DC2" character is in the first 1000 or so characters of the text file it will be downloaded, if those characters are after the first 1000 or so characters the file is displayed in the browser.

4

2 回答 2

2

当您向浏览器发送文件时,浏览器的行为将基于您的服务器发送的内容类型标头。如果您没有自己明确设置,您的 Web 服务器可能会尝试根据文件的前几个字节做出最佳猜测。

http://httpd.apache.org/docs/2.2/mod/mod_mime_magic.html

于 2013-10-08T20:49:50.357 回答
0

如果浏览器显示保存对话框,则确定顺序。

  • 由 Web 开发人员在 Apache 或 cgi 中设置的Content-Disposition 。按照规范,这是我们应该做的。
  • Content-Type 标头的MIME 类型由 Web 开发人员在 Apache 或 cgi 中设置

application/octet-stream ... browsers ... 将其视为 Content-Disposition 标头设置为附件,并提出“另存为”对话框。

  • Content-Type 标头的 MIME 类型由 Web 服务器确定和设置。例如 Apache 有两种方法:

    • Apache通过在 URI 或文件名中映射模式来分配 MIME 类型。例如AddType application/octet-stream .pkg
    • Apache 的mod_mime_magic如果它已由 Web 开发人员安装并启用)

    ...仅当魔法文件由 MimeMagicFile 指令指定时,此模块才处于活动状态。

  • Web开发人员在html文件或JS中设置的HTML5下载属性(我没有测试它是否不覆盖上述内容)

如果以上均不适用,则浏览器将超出规格并自行决定。

在以下屏幕截图中,响应标头未提及 Content-Disposition,也未提及 Content-Type。在左侧,我们可以看到文件的一部分被传输(我没有点击打开或保存),我们可以看到浏览器声明它是“应用程序/八进制流”

我对此的假设是,浏览器在收到文件的一部分后决定将其内联(在屏幕上)显示是不明智的,声明了 MIME 并提供了保存对话框。

浏览器截图

在我将文件的 URL 粘贴到 Omnibox 中,打开 DevTools 并在 Omnibox 中按 Enter 以“转到”粘贴的地址后,屏幕截图是从 Firefox 的开发人员工具制作的。

于 2022-01-23T15:06:33.370 回答