Laravel 使用阿里云 oss 存储对象

一、下载安装

composer require jacobcyl/ali-oss-storage

二、注册服务提供者

config/app.phpproviders下添加:

//阿里云OSS对象存储提供者
Jacobcyl\AliOSS\AliOssServiceProvider::class,

三、配置文件系统

app/filesystems.php中的disks里下添加:

'disks' => [
    
    //...
    'oss' => [
        'driver'     => 'oss',
        'access_id'  => '',//Your Aliyun OSS AccessKeyId
        'access_key' => '',//Your Aliyun OSS AccessKeySecret
        'bucket'     => '',//OSS bucket name
        'endpoint'   => 'oss-cn-shenzhen.aliyuncs.com', //<the endpoint of OSS, E.g: oss-cn-hangzhou.aliyuncs.com | custom domain, E.g:img.abc.com> OSS 外网节点或自定义外部域名
        //'endpoint_internal' => '', //<internal endpoint [OSS内网节点] 如:oss-cn-shenzhen-internal.aliyuncs.com> v2.0.4 新增配置属性,如果为空,则默认使用 endpoint 配置(由于内网上传有点小问题未解决,请大家暂时不要使用内网节点上传,正在与阿里技术沟通中)
        //'cdnDomain'  => '', //<CDN domain, cdn域名> 如果isCName为true, getUrl会判断cdnDomain是否设定来决定返回的url,如果cdnDomain未设置,则使用endpoint来生成url,否则使用cdn
        'ssl'        => false, // true to use 'https://' and false to use 'http://'. default is false,
        'isCName'    => false, // 是否使用自定义域名,true: 则Storage.url()会使用自定义的cdn或域名生成文件url, false: 则使用外部节点生成url
        'debug'      => true,
    ],
    //...
    
],

四、基础用法

Storage::disk('oss'); // 如果默认文件系统驱动程序是oss,则可以跳过此步骤

//获取指定存储桶的所有文件(请参阅upond配置)
Storage::files($directory);
Storage::allFiles($directory);

Storage::put('path/to/file/file.jpg', $contents); //第一个参数是目标文件路径,第二个参数是文件内容
Storage::putFile('path/to/file/file.jpg', 'local/path/to/local_file.jpg'); //从本地路径上传文件

Storage::get('path/to/file/file.jpg'); // 通过路径获取文件对象
Storage::exists('path/to/file/file.jpg'); // 确定存储(OSS)上是否存在给定文件
Storage::size('path/to/file/file.jpg'); // 获取文件大小(字节)
Storage::lastModified('path/to/file/file.jpg'); // 获取最后修改日期

Storage::directories($directory); // 获取给定目录中的所有目录
Storage::allDirectories($directory); // 获取给定目录中的所有(递归)目录

Storage::copy('old/file1.jpg', 'new/file1.jpg');//拷贝文件
Storage::move('old/file1.jpg', 'new/file1.jpg');//移动文件
Storage::rename('path/to/file1.jpg', 'path/to/file2.jpg');//重命名文件

Storage::prepend('file.log', 'Prepended Text'); // 在文件前面追加内容
Storage::append('file.log', 'Appended Text'); // 在文件后面追加内容

Storage::delete('file.jpg');//删除文件
Storage::delete(['file1.jpg', 'file2.jpg']);//删除多个文件

Storage::makeDirectory($directory); // 创建一个目录
Storage::deleteDirectory($directory); //递归删除目录。它将删除给定目录中的所有文件,因此请谨慎使用。

// 升级日志
// 适用于v2.0版本的新插件
Storage::putRemoteFile('target/path/to/file/jacob.jpg', 'http://example.com/jacob.jpg'); //通过远程URL将远程文件上传到存储
// v2.0.1版本的新功能
Storage::url('path/to/img.jpg'); // 获取文件网址

六、参考文档

packagist地址:https://packagist.org/packages/jacobcyl/ali-oss-storage

阿里云OSS官方文档:https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.49122215yuKg2N

猜你喜欢

转载自www.cnblogs.com/jxl1996/p/10307526.html