2017-09-01 49 views
0

我想從瀏覽器訪問pdf文件,該文件位於laravel存儲文件夾中。我不希望存儲是公開的。如何直接從瀏覽器訪問存儲器中的pdf文件?

我不想下載它(我設法做到了這一點)。我只想獲得一個獲取路線,並在瀏覽器中顯示該文件,如:www.test.com/admin/showPDF/123/123_321.pdf。

123是一個id。

如果我使用:

storage_path('app/'.$type.'/'.$fileName); 
or 
Storage::url('app/'.$type.'/'.$fileName); 

回報的完整服務器路徑。

謝謝。

回答

0

您可以從存儲文件夾中讀取它,然後將內容傳送到瀏覽器並強制瀏覽器下載它。

$path = storage_path('app/'.$type.'/'.$fileName) 

return Response::make(file_get_contents($path), 200, [ 
    'Content-Type' => 'application/pdf', //Change according to the your file type 
    'Content-Disposition' => 'inline; filename="'.$filename.'"' 
]); 
0

您可以存儲/程序/公共和公共/存儲之間的symbolink鏈接,以便您可以訪問您的文件,通過運行

php artisan storage:link 

更多信息Here

然後你就可以做出這樣的路徑來訪問文件:所以在這種情況下

Route::get('pdffolder/{filename}', function ($filename) 
{ 
    $path = storage_path('app/public/pdffolder/' . $filename); 

    if (!File::exists($path)) { 
     abort(404); 
    } 

    $file = File::get($path); 
    $type = File::mimeType($path); 

    $response = Response::make($file, 200); 
    $response->header("Content-Type", $type); 

    return $response; 
}); 

,如果你保存的文件名爲123.pdf PDF格式的文件夾中storage/app/public/pdffolder

you can access it by http://yourdomain.com/pdffolder/123.pdf 

你必須調整它有點,但我認爲這可以幫助你。

0

快速和骯髒,但你想要做的是使用你從控制器方法(或路由封閉,你的電話)響應中抓取的路徑。喜歡的東西:

public function sendPdf(Request $request) 
{ 
    // do whatever you need to do here, then 
    ... 
    // send the file to the browser 
    $path = storage_path('app/'.$type.'/'.$fileName); 
    return response()->file($path); 
} 

更多這方面的信息,請參閱https://laravel.com/docs/5.4/responses#file-responses,但是這就是我會去了解它

0

你要流式傳輸文件的請求。在你的控制器做以下的事情

use Symfony\Component\HttpFoundation\Response; 

... 

function showPdf(Request $request, $type, $fileName) 
{ 
    $content = file_get_contents(storage_path('app/'.$type.'/'.$fileName)); 

    return Response($content, 200, [ 
      'Content-Type' => 'application/pdf', 
      'Content-Disposition' => "inline; filename=\"$fileName\"" 
     ]); 
} 

這將直接流您的PDF

0

增加新路線獲得PDF

Route::get('/admin/showPDF/{$type}/{$fileName}','[email protected]'); 

,並在控制器

public function pdf($type,$fileName) 
    { 
     $path = storage_path('app/'.$type.'/'.$fileName); 
     return response()->file($path); 
    } 
相關問題