2009-10-20 87 views
8

人们,我知道有很多关于强制下载对话框弹出的线程,但没有解决方案为我工作。PHP:强制文件下载和IE,再次

我的应用程序发送邮件到用户的电子邮件帐户,通知他们“另一个用户给他们发送了一条消息”。这些消息可能会链接到Excel文件。当用户点击他们的GMail/Yahoo Mail/Outlook中的链接到该Excel文件时,我想要弹出文件保存对话框。

问题:当我在IE上右键单击并执行“另存为”时,出现另存为对话框。当我点击链接(我的许多客户会这样做,因为他们不懂电脑),我得到一个IE错误信息:“IE无法从...下载文件...”。可能是相关的:在我正在测试的GMail上,每个链接都是“target = _blank”链接(由Google强制执行)。

所有其他浏览器在所有情况下均可正常工作。

这里是我的头文件(通过小提琴手捕获):

HTTP/1.1 200 OK 
Proxy-Connection: Keep-Alive 
Connection: Keep-Alive 
Content-Length: 15872 
Via: **** // proxy server name 
Expires: 0 
Date: Tue, 20 Oct 2009 22:41:37 GMT 
Content-Type: application/vnd.ms-excel 
Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_python/3.3.1 Python/2.5.2 SVN/1.4.6 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 
Cache-Control: private 
Pragma: no-cache 
Last-Modified: Tue, 20 Oct 2009 22:41:37 GMT 
Content-Disposition: attachment; filename="myFile.xls" 
Vary: Accept-Encoding 
Keep-Alive: timeout=5, max=100 

我想IE的定期左键点击行为的工作。有任何想法吗?

回答

13

这将检查IE的版本并相应地设置标题。

// assume you have a full path to file stored in $filename 
if (!is_file($filename)) { 
    die('The file appears to be invalid.'); 
} 

$filepath = str_replace('\\', '/', realpath($filename)); 
$filesize = filesize($filepath); 
$filename = substr(strrchr('/'.$filepath, '/'), 1); 
$extension = strtolower(substr(strrchr($filepath, '.'), 1)); 

// use this unless you want to find the mime type based on extension 
$mime = array('application/octet-stream'); 

header('Content-Type: '.$mime); 
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: '.sprintf('%d', $filesize)); 
header('Expires: 0'); 

// check for IE only headers 
if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false)) { 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
} else { 
    header('Pragma: no-cache'); 
} 

$handle = fopen($filepath, 'rb'); 
fpassthru($handle); 
fclose($handle); 
+0

谢谢SOOO多。救了我!而我又回到理智了:) – 2009-10-21 01:11:11

+1

后检查和预检不做你认为他们做的事情。你应该把它们拿出来。 – EricLaw 2009-10-25 16:29:08

+0

增加了对IE 11的支持,并修复了代码中的错误。 – 2014-03-06 17:52:14

2

如果您尝试每次都要下载文件,请将内容类型更改为'application/octet-stream'。

尝试不使用杂注语句。

5

只需使用:

header('Content-Disposition: attachment'); 

这就是全部。 (Facebook也一样。)