借鉴了一些优秀的代码,打造Laravel最好的OSS Storage扩展
安装
只需将下面这行
"jacobcyl/ali-oss-storage": "2.1"
添加到你项目的composer.json require内. 然后运行 composer update.
Or, you can simple run below command
"composer require jacobcyl/ali-oss-storage:2.1"
来安装
在 config/app.php 文件中添加provider
Jacobcyl\AliOSS\AliOssServiceProvider::class,
配置
配置 app/filesystems.php:
'disks'=>[
...
'oss' => [ 'driver' => 'oss', 'access_id' => '<你阿里云 AccessKeyId>', 'access_key' => '<你阿里云 AccessKeySecret>', 'bucket' => '', 'endpoint' => '<节点名称或自定义域名>', // OSS 外网节点或自定义外部域名 //'endpoint_internal' => '<internal endpoint [OSS内网节点] 如:oss-cn-shenzhen-internal.aliyuncs.com>', // v2.0.4 新增配置属性,如果为空,则默认使用 endpoint 配置(由于内网上传有点小问题未解决,请大家暂时不要使用内网节点上传,正在与阿里技术沟通中) 'cdnDomain' => '', // 如果isCName为true, getUrl会判断cdnDomain是否设定来决定返回的url,如果cdnDomain未设置,则使用endpoint来生成url,否则使用cdn 'ssl' => true, // true to use 'https://' and false to use 'http://'. default is false, 'isCName' => false, // 是否使用自定义域名,true: 则Storage.url()会使用自定义的cdn或域名生成文件url, false: 则使用外部节点生成url 'debug' => true, ],...
]
使用:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
public function photo(Request $request){
if($request->isMethod('post')){
$file=$request->file('file');
if($file->isValid()){
//获取文件的原文件名 包括扩展名
//$yuanname= $file->getClientOriginalName();
//获取文件的扩展名
//$kuoname=$file->getClientOriginalExtension();
//获取文件的类型
//$type=$file->getClientMimeType();
//获取文件的绝对路径,但是获取到的在本地不能打开
$path=$file->getRealPath();
//要保存的文件名 时间+扩展名
$filename='avatars/'.date('Y-m-d').'/'. uniqid() .'.'.'png';
//保存文件 配置文件存放文件的名字 ,文件名,路径
$bool= Storage::disk('oss')->put($filename,file_get_contents($path));
dd($bool);
}
}
return view('admincp.index.photo');
}