2012-05-25 99 views
0

因此,我將文件存儲在Amazon S3上。我的客戶從我們的網站下載這些文件,他們點擊下載,並將信息發送到我們的download.php頁面(客戶看不到此頁面),但是它使用PHP獲取文件名和路徑(代碼如下) 。但是我們遇到的問題是它沒有告訴瀏覽器文件大小,所以當客戶下載時,他們會看到「剩餘時間未知」。我該如何做到這一點,以便download.php頁面可以獲取該信息並單獨傳遞?從S3下載文件大小

<?php 

$file_path = "http://subliminalsuccess.s3.amazonaws.com/"; 
$file_name = $_GET['download']; 
$file = file_get_contents('$file_name'); 

header('application/force-download'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="'.$file_name.'"'); 

$pos = strpos($file_name, "http"); 

if ($pos !== false && $pos == 0) 
{ 
readfile($file_name); 
} else readfile($file_path.$file_name); 

?> 

回答

1

這很容易。看,當你做file_get_contents()時,你可以用strlen()來獲得你的文件大小。然後你在響應中發送Content-Length頭部。

<?php 

$file_path = 'http://subliminalsuccess.s3.amazonaws.com/'; 
$file  = trim($_GET['download']); 
$file_name = $file_path.$file; 

$file_contents = file_get_contents($file_name) 
    OR die('Cannot get the file: '.$file); 

header('Content-Type: application/force-download'); 
header('Content-Type: application/octet-stream'); 
header('Content-Length: '.strlen($file_contents)); 
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 

echo $file; 

順便說一句,在你的代碼中有太多的錯誤。例如,您使用file_get_contents()讀取兩次文件,使用readfile()讀取第二次文件。 $ file_name變量沒有URI。 file_get_contents('$ file_name')也是錯誤的。

而且,你不檢查收到的網址,而只是ReadFile的(),它是有人可能通過的任何URL到你的腳本是不是很好...

+0

感謝你的幫助。我對PHP知之甚少,而且我實際上並沒有編寫代碼,但是這裏沒有人能夠弄清楚這一點,所以我負責編寫代碼。然而,當我使用上面粘貼的代碼時,它實際上認爲文件大小是50字節,而實際上它的MP3更可能是300 MB或更大。 –

+0

有趣...我不知道爲什麼。你確定這是正確的文件嗎?另一種選擇是使用http://aws.amazon.com/sdkforphp/。您可以通過API獲取文件,從響應中獲取Content-Length並按照我向您展示的方式進行。 –

+0

它的def是正確的文件,因爲如果我回到我們原來的代碼(未顯示),它下載完美,只是沒有顯示剩餘時間和文件大小。即時將要檢查出現在的API鏈接。感謝您的幫助,非常感謝。 –