laravel-admin實現圖片上傳oss
阿新 • • 發佈:2021-01-07
技術標籤:laravel-adminphplavarel伺服器
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);
});
}
}