How to get file URL using Storage facade in laravel 5?

前端 未结 13 644
庸人自扰
庸人自扰 2020-11-30 22:40

I\'ve been experimenting using the new Flysystem integration with Laravel 5. I am storing \'localised\' paths to the DB, and getting the Storage facade to complete the path

相关标签:
13条回答
  • 2020-11-30 23:19

    Store method:

    public function upload($img){
       $filename = Carbon::now() . '-' .  $img->getClientOriginalName();
       return Storage::put($filename, File::get($img)) ? $filename : '';
    }
    

    Route:

     Route::get('image/{filename}', [
            'as'   => 'product.image',
            'uses' => 'ProductController@getImage',
        ]);
    

    Controller:

     public function getImage($filename)
        {
            $file = Storage::get($filename);
    
            return new Response($file, 200);
        }
    

    View:

     <img src="{{ route('product.image', ['filename' => $yourImageName]) }}" alt="your image"/>
    
    0 讨论(0)
  • 2020-11-30 23:21

    If you just want to display storage (disk) path use this:

    Storage::disk('local')->url('screenshots/1.jpg'); // storage/screenshots/1.jpg
    Storage::disk('local')->url(''): // storage
    

    Also, if you are interested, I created a package (https://github.com/fsasvari/laravel-uploadify) just for Laravel so you can use all those fields on Eloquent model fields:

    $car = Car::first();
    
    $car->upload_cover_image->url();
    $car->upload_cover_image->name();
    $car->upload_cover_image->basename();
    $car->upload_cover_image->extension();
    $car->upload_cover_image->filesize();
    
    0 讨论(0)
  • 2020-11-30 23:24

    This is how I got it to work - switching between s3 and local directory paths with an environment variable, passing the path to all views.

    In .env:

    APP_FILESYSTEM=local or s3
    S3_BUCKET=BucketID
    

    In config/filesystems.php:

    'default' => env('APP_FILESYSTEM'),
    

    In app/Providers/AppServiceProvider:

    public function boot()
    {
        view()->share('dynamic_storage', $this->storagePath());
    }
    
    protected function storagePath()
    {
        if (Storage::getDefaultDriver() == 's3') {
            return Storage::getDriver()
                    ->getAdapter()
                    ->getClient()
                    ->getObjectUrl(env('S3_BUCKET'), '');
        }
    
        return URL::to('/');
    }
    
    0 讨论(0)
  • This method exists since Laravel 5.4, you can get it by:

    $path = Storage::disk('public')->path($filename);
    
    0 讨论(0)
  • 2020-11-30 23:25

    First get file url/link then path, as below:

    $url = Storage::disk('public')->url($filename);
    $path = public_path($url);
    
    0 讨论(0)
  • 2020-11-30 23:26

    Another solution I found is this:

    Storage::disk('documents')->getDriver()->getConfig()->get('url')
    

    Will return the url with the base path of the documents Storage

    0 讨论(0)
提交回复
热议问题