Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using laravel 5.3, I am trying to retrieve an image in a view. How I could do this? folder structure: storage/app/avatard

Here is the code:

public function storeAvatar(Request $request, $username)
{
  $user = User::where('name', $username)->first();
  $avatar = $request->file('avatar')->store('avatars');

  $avatar = explode('avatars/', $avatar);



  $user->user_setting()->updateOrCreate(
    ['user_id' => $user->id],
    ['avatar' => $avatar[1]]
  );

  return back();
}

This is how the image path is saved in the database:

/users/avatar/default.png

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
678 views
Welcome To Ask or Share your Answers For Others

1 Answer

Somewhat like this you can achieve as storage path is directly unavailable for public. you need to provide public url in route like this.

In view

<img src="{{route('avatar',$filename)}}" />

or

<img src="/avatars/{{$filename}}" />

In routes/web.php

Route::get('/avatars/{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;
})->name('avatar');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...