2016-04-10 173 views
0

如何獲取位於存儲中的文件?Laravel存儲外觀和檢索文件

我建立了一條路線並將它指向[email protected]。方法如下

public function myMethod() 
{ 
    $validPath = 'valid-path-inside-local-storage'; 
    $file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath); 
    return $file; 
} 

但是我得到的是亂碼,可能是原始數據。如果文件是圖像或如果文件是a.xls,那麼如何讓瀏覽器顯示圖像?

回答

0
$validPath = 'valid-path-inside-local-storage'; 
    $mimeType = Storage::mimeType($validPath); 
    $file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath); 
    return (new Response($file, 200)) 
     ->header('Content-Type', $mimeType); 

我希望我沒有錯過任何東西。

0

爲了您的路線定義是:

Route::get('docs/{file}', '[email protected]'); 

而這個控制器

class DocumentController extends BaseController 
{ 
    public function getDoc($file){ 
     $path = 'pathToDirectory/'.$file; 
     if(Storage::disk('yourDisk')->exists($path)){ 
     $attachment = Storage::disk('yourDisk')->get($path); 
     $type = Storage::disk('yourDisk')->mimeType($path); 
     return Response::make($attachment, 200)->header("Content-Type", $type); 
     }else{ 
     return Response::json('This file does not exists.'); 
     } 
    } 
}