HTTP Headers简明易懂的教程(8)

http://www.itjxue.com  2015-07-17 08:18  来源:未知  点击次数: 

Content-Type

这个头部包含了文档的”mime-type”。浏览器将会依据该参数决定如何对文档进行解析。例如,一个html页面(或者有html输出的php页面)将会返回这样的东西:

Content-Type: text/html; charset=UTF-8

‘text’ 是文档类型,‘html’则是文档子类型。 这个头部还包括了更多信息,例如 charset。

如果是一个图片,将会发送这样的响应:

Content-Type: image/gif

浏览器可以通过mime-type来决定使用外部程序还是自身扩展来打开该文档。如下的例子降调用Adobe Reader:

Content-Type: application/pdf

直接载入,Apache通常会自动判断文档的mime-type并且添加合适的信息到头部去。并且大部分浏览器都有一定程度的容错,在头部未提供或者错误提供该信息的情况下它会去自动检测mime-type。

你可以在这里找到一个常用mime-type列表。

在PHP中你可以通过 finfo_file() 来检测文件的ime-type。

Content-Disposition

这个头部信息将告诉浏览器打开一个文件下载窗口,而不是试图解析该响应的内容。例如:

Content-Disposition: attachment; filename="download.zip"

他会导致浏览器出现这样的对话框:

注意,适合它的Content-Type头信息同时也会被发送

Content-Type: application/zip
Content-Disposition: attachment; filename="download.zip"

Content-Length

当内容将要被传输到浏览器时,服务器可以通过该头部告知浏览器将要传送文件的大小(bytes)。

Content-Length: 89123

对于文件下载来说这个信息相当的有用。这就是为什么浏览器知道下载进度的原因。

例如,这里我写了一段虚拟脚本,来模拟一个慢速下载。

// it's a zip file
header('Content-Type: application/zip');
// 1 million bytes (about 1megabyte)
header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
echo str_repeat(".",1000);
// sleep to slow down the download
usleep(50000);
}

结果将会是这样的:

现在,我将Content-Length头部注释掉:

// it's a zip file
header('Content-Type: application/zip');
// the browser won't know the size
// header('Content-Length: 1000000');
// load a download dialogue, and save it as download.zip
header('Content-Disposition: attachment; filename="download.zip"');
// 1000 times 1000 bytes of data
for ($i = 0; $i < 1000; $i++) {
echo str_repeat(".",1000);
// sleep to slow down the download
usleep(50000);
}

结果就变成了这样:

这个浏览器只会告诉你已下载了多少,但不会告诉你总共需要下载多少。而且进度条也不会显示进度。

(责任编辑:IT教学网)

更多