[英]LARAVEL - Displaying images from the storage folder
我是Laravel的新手,想知道是否有人可以通過簡單的圖片上傳來幫助我。
我有一個表單,允許用戶在此過程中為其個人資料創建個人資料和上傳以及頭像。 一切都很完美。 這是我的控制器的代碼:
if (request()->hasFile('avatar')) {
$file = request()->file('avatar');
$file->storeAs('avatars/' . auth()->id(), 'avatar.jpg');
}
圖像保存在storage / app / avatars / USER-ID / avatar.jpg中
我不確定如何顯示此文件夾中的圖像。 我找了解決方案,但我無法使用php artisan storage:link
因為它不是我的服務器。 如何在不使用存儲鏈接的情況下解決此問題? 我可以手動創建鏈接嗎?
如果有人能向我解釋一個完美的解決方案!
只需詢問您是否需要任何代碼段。
謝謝!
您需要使用插入控制器的路徑訪問受保護的文件,該控制器可以訪問文件並將其傳遞給視圖。
我還建議使用它可以安裝的包intervention/image
composer require intervention/image
有關訪問圖像的信息,請參見下文:
//您在web.php
路線
// Public route to show user avatar
Route::get('avatars/{id}/{image}', [
'uses' => 'TheNameOfYourController@userProfileAvatar'
]);
//在您的控制器文件中。 在這個例子中,根據我們上面的名稱,它將是userProfileAvatar()
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;
class TheNameOfYourController extends Controller
{
/**
* Show user avatar
*
* @param $id
* @param $image
* @return string
*/
public function userProfileAvatar($id, $image)
{
return Image::make(storage_path() . '/avatars/' . $id . '/' . $image)->response();
}
}
//您的刀片視圖顯示圖像
<img src="images/profile/{{ \Auth::user()->id }}/avatar.jpg" alt="{{ \Auth::user()->name }}">
以下是一些參考文獻,但這些內容更進一步,並在上傳時保存數據庫的文件路徑:
//路由示例
//控制器示例
//查看示例
好吧,如果您無權訪問服務器以創建符號鏈接,則需要創建一個將圖像作為響應返回的路徑。
像這樣的東西:
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('avatars/' . $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;
});
創建一個符號鏈接,用於連接storage/app
和public/img
目錄,例如:
ln -s /home/laravel/public/img /home/laravel/storage/app
然后只需使用asset()
幫助器生成一個鏈接:
<img src="{{ asset('img/avatars/'.auth()->id().'/avatar.jpg') }}">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.