1.安装扩展包jacobcyl/ali-oss-storage": "^2.1
composer require jacobcyl/ali-oss-storage:^2.1
2.然后在 config/app.php 文件中注册 Jacobcyl\AliOSS\AliOssServiceProvider :
'providers' => [
// Other service providers...
Jacobcyl\AliOSS\AliOssServiceProvider::class,
],
3.然后需要在 config/filesystems.php 文件中的 disks 中添加 OSS 的配置信息
'disks' => [
'qiniu' => [
'driver' => 'qiniu',
'access_key' => env('QINIU_ACCESS_KEY'),
'secret_key' => env('QINIU_SECRET_KEY'),
'bucket' => env('QINIU_BUCKET'),
'domain' => env('QINIU_DOMAIN'),
],
'oss' => [
'driver' => 'oss',
'access_id' => env('ALIYUN_ACCESS_ID'),
'access_key' => env('ALIYUN_ACCESS_KEY'),
'bucket' => env('ALIYUN_BUCKET'),
'endpoint' => env('ALIYUN_ENDPOINT'),
'cdnDomain' => env('ALIYUN_CDN_DOMAIN'),
'ssl' => env('ALIYUN_SSL'),
'isCName' => env('ALIYUN_IS_CNAME'),
'debug' => env('ALIYUN_DEBUG')
],
4.然后在 .env 文件中进行配置
FILESYSTEM_DRIVER=oss
ALIYUN_ACCESS_ID=
ALIYUN_ACCESS_KEY=
ALIYUN_BUCKET=//列表块名称
ALIYUN_ENDPOINT=自定义域名加http 如http://image.xxx.com
ALIYUN_CDN_DOMAIN=自定义域名加http 与上一个参数一样
ALIYUN_SSL=false
ALIYUN_IS_CNAME=true
ALIYUN_DEBUG=false
5.写service层的服务
<?php
namespace App\Service\AliyunOss;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\File;
class AliOss
{
/***
* 阿里云OSS上传
* @param $path 阿里云oss上的路径 自己填写
* @param $file file[]表单接受到的文件
* @param string $drive
*/
public static function aliOss($path, $file, $drive = 'oss')
{
//设置存储引擎
$disk = Storage::disk($drive);
try{
//多文件 单文件上传
foreach ($file as $key=>$value)
{
//文件上传返回url
$data=$disk->putfile($path,$value);
//多图片url存到数组
$dataPath[] =$data;
}
}catch (\Exception $e){
return '上传失败';
}
//返回单图片或多图片路径
//图片路径加域名
foreach ($dataPath as $value)
{
$filePath[] = env('ALIYUN_CDN_DOMAIN').'/'.$value;
}
return $filePath;
}
}
6.Controller文件
<?php
namespace App\Http\Controllers\Admin;
use App\Service\AliyunOss\AliOss;
use App\Common\SuccessBaseObj;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
/**
* Class AliyunOssController
* @package App\Http\Controllers\Admin
* 多图上传阿里OSS例子
*/
class AliyunOssController extends Controller
{
public function file(Request $request)
{
$file = $request->file('file');
$validate = Validator::make($file,['required|image|max:153600']);
if($validate->fails()){return $this->fail($validate->errors()->first());}
//调用服务上传文件 接收返回的文件url路径
$result=AliOss::aliOss('uploads/file/'.date('Ymd'),$file);
return SuccessBaseObj::getSucObjByMsg($result);
}
}
用postman测试
参考 https://blog.csdn.net/hl449006540/article/details/85015782
https://learnku.com/laravel/t/35638