2012-07-25 52 views
1

我已經獲得了關於使用PHP 我有以下代碼下載jpg和.avi文件從服務器問題:PHP下載.jpg或.AVI

$fileName = "Koala.jpg"; 
$filePath = "./Koala.jpg"; 
if (!file_exists($filePath)){ 
    echo "No file"; 
    return; 
} 
$fp = fopen($filePath, "r"); 
$fileSize = filesize($filePath); 
header("Content-type: application/octet-stream"); 
header("Accept-Ranges: bytes"); 
header("Content-Length: $fileSize"); 
header("Content-Disposition: attachment;filename=".$fileName); 

$buffer = 1024; 
while(!feof($fp)){ 
    $data = fread($fp, $fileSize); 
    echo $data; 
} 
fclose($fp); 

代碼下載txt文件,併成功下載的文件可以被讀取。 但是,當涉及到.jpg時,無法讀取下載的.jpg文件。 任何人都可以伸出援手嗎?由於

剛纔想的另一種方法,它工作正常

$file = 'Koala.jpg'; 

if (file_exists($file)) { 
header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename='.basename($file)); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($file)); 
ob_clean(); 
flush(); 
readfile($file); 
exit; 
} 

但只是不知道是什麼原因導致第一種方法失敗,即使使用的fopen(「XXX」,「RB」)來代替。謝謝

+0

什麼是你的特定錯誤得到些什麼? – BenOfTheNorth 2012-07-25 10:07:22

+0

該錯誤表示該文件可能已損壞。 – 2012-07-25 10:11:39

+1

謝謝大家。問題可能是由於輸出緩衝區。在回顯數據之前添加ob_clean以擦除輸出緩衝區後,問題就解決了。 – 2012-07-25 13:33:04

回答

0

嘗試替換image/jpeg的application/octet-stream。

問候

+0

剛試過,但系統給出了同樣的錯誤。 – 2012-07-25 10:13:19

+0

看到這個:http://www.finalwebsites.com/forums/topic/php-file-download – esmoreno 2012-07-25 10:15:21

0

我不是PHP的專家(抱歉地說),但我記得在Windows服務器上使用PHP時有類似的問題。它源於打開沒有二進制標誌的文件(樣本中應爲fopen($filePath, "rb");)。如果您沒有設置該標誌,那麼當您從可能會破壞文件的流中讀取數據時,數據可能會發生變化(並且您不會在文本文件中注意到它)。

請參閱http://www.php.net/manual/en/function.fopen.php瞭解更多有關不同模式的信息。

0

嘗試使用此 -

<?php 
$filename = "MyImage.jpg"; 
$handle = fopen($filename, "rb"); 
$contents = fread($handle, filesize($filename)); 
fclose($handle); 
?> 
0

,而不是下面的代碼,您正在使用,

$buffer = 1024; 
while(!feof($fp)){ 
    $data = fread($fp, $fileSize); 
    echo $data; 
} 

只需使用readfile方法

readfile($filePath);