我有一个指向PHP脚本的链接,该脚本生成一个CSV文件以进行下载和保存。我在响应中生成Content-Disposition和Content-Type header 。除Chrome浏览器(v19)之外,每个浏览器都可以正常下载文件。
链接是这样的:
http://hostname.com/controller/action/export
从该请求返回的 header 是:
Cache-control:no-cache, must-revalidate
Connection:Keep-Alive
Content-Disposition:attachment; filename=2012-03-14.csv
Content-Encoding:gzip
Content-Length:521
Content-Type:application/vnd.ms-excel
Date:Thu, 15 Mar 2012 05:17:55 GMT
Expires:Mon, 26 Jul 1997 05:00:00 GMT
Keep-Alive:timeout=5, max=92
P3P:CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Pragma:no-cache
Server:Apache/2.2.11 (Win32) mod_ssl/2.2.11 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.9
Vary:Accept-Encoding
X-Powered-By:PHP/5.2.9
Chrome开发人员工具显示网络连接为
Canceled
,并且控制台窗口显示以下错误:Resource interpreted as Document but transferred with MIME type application/vnd.ms-excel:
我尝试对Content-Type使用不同的值,但我已关闭了Cache-Control和Content-Type header 。我已经使用Javascript
location.href=
,<a>
标记,<form action="POST">
,关闭了Gzip压缩和其他各种方法进行了测试,试图使Chrome实际下载文件。其他所有浏览器都可以正常下载文件,因此我的问题是:是什么导致Chrome将请求解释为“文档”而不是附件显示?是否有我遗漏的另一个 header 或列表中的 header 使它感到困惑?
编辑:这是所请求的PHP代码,尽管有点长:
function renderHeaders($filename = null) {
header("Content-Type: application/vnd.ms-excel");
header("Cache-Control: public, must-revalidate, max-age=0");
if (is_string($filename)) {
$this->setFilename($filename);
}
if ($this->filename === null) {
$this->filename = 'Data.csv';
}
if ($this->filename) {
header("Content-disposition: attachment; filename=".$this->filename);
}
}
function render($outputHeaders = true, $to_encoding = null, $from_encoding = "auto") {
if ($outputHeaders) {
$this->renderHeaders();
}
if ($this->_tmpFile) {
rewind($this->buffer);
$output = '';
while (!feof($this->buffer)) {
$output .= fread($this->buffer, 8192);
}
fclose($this->buffer);
} else {
rewind($this->buffer);
$output = stream_get_contents($this->buffer);
}
// get around excel bug (http://support.microsoft.com/kb/323626/)
if (substr($output,0,2) == 'ID') {
$pos = strpos($output, $this->delimiter);
if ($pos === false) {
$pos = strpos($output, "\n");
}
if ($pos !== false) {
$output = $this->enclosure . substr($output, 0, $pos) . $this->enclosure . substr($output, $pos);
}
}
if ($to_encoding) {
$output = mb_convert_encoding($output, $to_encoding, $from_encoding);
}
$this->clear();
return $this->output($output);
}
最佳答案
内容类型错误,应为text/csv
,而不是application/vnd.ms-excel
。
资料来源:Wikipedia