2009-10-20 29 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也一樣。)