Retrieving image stored in storage folder

£可爱£侵袭症+ 提交于 2019-12-17 21:33:13

问题


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


回答1:


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



回答2:


First create a storage link by typing in

php artisan storage:link

and then

<img src={{ asset('storage/folder_name/image_name') }} />



回答3:


If you store your files in the storage/app/public directory as per the Laravel documentation you can create a symbolic link on Unix/Linux systems that will allow you to reference the files as if they were in the public directory.

Create the symbolic link using the artisan command:

php artisan storage:link

In your views you are then able to reference the files using

{{ asset('storage/path/to/file.png') }}



回答4:


Consider if you are using Homestead, you must create the symbolic link from the virtual machine;

In your terminal:

homestead ssh

go to your project folder:

cd Code/YOUR_PROJECT

now you can execute the command:

php artisan storage:link


来源:https://stackoverflow.com/questions/41138642/retrieving-image-stored-in-storage-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!