2014-01-13 92 views
0

我想創建一個鏈接,從服務器計算機的根目錄下使用php下載excel文件。所以我寫了一個簡單的代碼如下,用php下載文件

<?php 

    header("Content-disposition: attachment;  filename=example.xls"); 

    header("Content-type: application/vnd.ms-excel"); 

    readfile("example.xls"); 

    ?> 

它就能被然而,當我想打開它下載了,我得到了錯誤說我下載的文件是不同的格式不是由文件擴展名指定。我也嘗試了與jpeg文件相同的方法,並沒有得到相同的錯誤,但是當我點擊它時,它什麼也沒有顯示。有人能幫我嗎?我不是很擅長編程。先謝謝你!

+0

當我有這樣的問題,我通常先註釋掉'頭排除他們()'函數,這樣我可以看到,它的實際發送正確的數據。您還可以將服務器上的example.xls與保存到工作站的example.xls進行比較,以確保它們相同。 –

回答

1

試試這個

$file='example.xls'; $filesize=filesize($file); 
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); 
header("Pragma: no-cache"); 
    header('Content-type: application/vnd.ms-excel'); 
header('Content-Disposition: inline; filename="'.basename($file).'"'); 
header("Content-Length: " . $filesize); 
$fh = fopen("$file, "rb"); 

// output file 
while(!feof($fh)) 
{ 
# output file without bandwidth limiting 
    print(fread($fh, filesize($file))); 
} 
fclose($fh); 
+0

我用我的舊網站下載第n個文件 –

+0

謝謝你的迴應。我嘗試過,但它給出錯誤'沒有收到數據'。 – user3428185

+0

我已編輯它,它現在對我來說工作正常 –