laravel-admin实现图片上传oss

laravel-admin实现图片上传oss

安装发布AliOSS-storage

下载

composer require jacobcyl/ali-oss-storage:^2.1

在config/app.php 中providers数组增加代码

Jacobcyl\AliOSS\AliOssServiceProvider::class,

添加配置

在config/filesystem.php 中disks数组中增加代码, 其中access_id,access_key,bucket,endpoint参数都是到阿里云提供

'oss' => [
        'driver'     => 'oss',
        'access_id'  => env('ALIYUN_ACCESS_KEY_ID'),
        'access_key' => env('ALIYUN_ACCESS_KEY_SECRET'),
        'bucket'     => env('ALIYUN_OSS_BUCKET'),
        'endpoint'   => env('ALIYUN_OSS_ENDPOINT'),
        'url'        => env('ALIYUN_OSS_URL'),
        'ssl'        => true,
        'isCName'    => false,
        'debug'      => false,
    ],

设置默认驱动为oss

'default' => env('FILESYSTEM_DRIVER', 'oss'),

在config/admin.php中修改upload配置

 'upload' => [

        // Disk in `config/filesystem.php`.
        'disk' => 'oss',

        // Image and file upload path under the disk above.
        'directory' => [
            'image' => 'images',
            'file'  => 'files',
        ],
    ],

在controller中的form 方法中设置字段组件为image或者file, 如果是image,那么文件存在images目录下,如果是file, 那么存在files目录下,move方法就是设置上传路径

$form->image('image', 'PC轮播图')
    ->move('/'.config('app.name').'/news_pc');

这样文件上传后,数据库会保存阿里云返回的相对路径到 image 字段中
如果需要把绝对路径保持到数据库,那么可以在model 中的boot方法中修改。

class AdModel extends Model {
    
    

    protected $table = "ad";
    public $timestamps = false;

    public static function boot(){
    
    
        // 继承父类
        parent::boot();

        // updating creating saving 这几个方法你自己选择,打印一下$model看看你就知道怎么取出数据了
        static::creating(function ($model) {
    
    
            $hostUrl= \env("ALIYUN_OSS_URL");
            $model->img_src = $hostUrl . $model->img_src;
            $model->created_at = time();
        });

        static::updating(function ($model) {
    
    
            $hostUrl = \env("ALIYUN_OSS_URL");
            $model->img_src = $hostUrl . str_replace($hostUrl,"", $model->img_src);
        });

    }
}

猜你喜欢

转载自blog.csdn.net/CharmHeart/article/details/112261398