Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

laravel - Retrieving image stored in storage folder

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

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

1 Reply

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...