2015-07-20 101 views
0

我使用Laravel的存儲門面下載PDF文件,我能夠上傳PDF到S3,我也能得到()的內容,但我不能顯示或將其下載到最終用戶作爲實際的pdf文件。它看起來像原始數據。這裏是代碼:Laravel 5.1 - 如何從S3鬥

$file = Storage::disk($storageLocation)->get($urlToPDF); 
header("Content-type: application/pdf"); 
header("Content-Disposition: attachment; filename='file.pdf'"); 
echo $file; 

這怎麼辦?我檢查了幾篇文章(和SO),但他們都沒有爲我工作。

回答

-2

我想通了。愚蠢的錯誤。我不得不從文件名中刪除單引號。

修復:

$file = Storage::disk($storageLocation)->get($urlToPDF); 
header("Content-type: application/pdf"); 
header("Content-Disposition: attachment; filename=file.pdf"); 
echo $file; 
+0

爲什麼這個downvoted即使它被接受? –

+0

這是一個不好的解決方案 –

2

你可以創建一個下載網址,使用getObjectUrl方法

財產以後這樣的:

$downloadUrl = $s3->getObjectUrl($bucketname, $file, '+5 minutes', array(
      'ResponseContentDisposition' => 'attachment; filename=$file,'Content-Type' => 'application/octet-stream', 
    )); 

和URL傳遞給用戶。這將引導用戶進入一個amzon頁面,該頁面將開始文件下載(該鏈接將有效5分鐘 - 但你可以改變它)

另一種選擇,首先將該文件保存到您的服務器,然後讓用戶從您的服務器下載文件

4

我覺得這樣的事情會做的工作在15.2:

public function download($path) 
{ 
    $fs = Storage::getDriver(); 
    $stream = $fs->readStream($path); 
    return \Response::stream(function() use($stream) { 
     fpassthru($stream); 
    }, 200, [ 
     "Content-Type" => $fs->getMimetype($path), 
     "Content-Length" => $fs->getSize($path), 
     "Content-disposition" => "attachment; filename=\"" .basename($path) . "\"", 
     ]); 
} 
0
$filename = 'test.pdf'; 
$filePath = storage_path($filename); 

$header = [ 
    'Content-Type' => 'application/pdf', 
    'Content-Disposition' => 'inline; filename="'.$filename.'"' 
]; 

return Response::make(file_get_contents($filePath), 200, $header); 
+3

感謝您的第一篇文章。在答案中發佈代碼時,儘量避免僅發佈代碼塊,通過提供有關更改內容和原因的解釋來擴展答案。請參閱[社區指南](https://stackoverflow.com/help/how-to-answer)撰寫一個好的答案。 – LightBender

+2

有一點解釋可以幫助你更好地理解你的答案。 – Annjawn