Larave 结合用阿里云 OSS 作为 Storage 存储文件

作者: JONE 分类: PHPer 发布时间: 2020-05-26 16:48

原链接 https://learnku.com/laravel/t/2165/larave-combined-with-ali-cloud-oss-as-storage-storage-file

Aliyun-oss-storage for Laravel 5+

借鉴了一些优秀的代码,综合各方,同时做了更多优化,将会添加更多完善的接口和插件,打造 Laravel 最好的 OSS Storage 扩展

参考

Require

  • Laravel 5+
  • cURL extension

安装

只需将下面这行

"jacobcyl/ali-oss-storage": "dev-master"

添加到你项目的 composer.json require 内。然后运行 composer install or composer update.
Or, you can simple run below command

"composer require jacobcyl/ali-oss-storage:dev-master"

来安装
config/app.php 文件中添加 provider

Jacobcyl\AliOSS\AliOssServiceProvider::class,

配置

配置 app/filesystems.php:

    'disks'=>[
        ...
        'oss' => [
                'driver'        => 'oss',
                'access_id'     => '<你阿里云 AccessKeyId>',
                'access_key'    => '<你阿里云 AccessKeySecret>',
                'bucket'        => '<OSS bucket 名称>',
                'endpoint'      => '<节点名称或自定义域名>',
                'isCName'       => <如果上面使用了节点名称,这里设置为false,如果使用了自定义域名,为true>,
                'debug'         => '<true|false>',
        ],
        ...
    ]

设置默认驱动 app/filesystems.php:

    'default' => 'oss',

好了,设置完成后,你就可以像平时使用 storage 一样使用阿里云 OSS 了

使用

具体使用也可以参考官方 Storage 文档 Larave doc for Storage
常用接口如下

首先引入 Storage facade

use Storage;

接下来就可以适用所有 Storage 接口,这里也新增了一些接口

Storage::disk('oss'); // if default filesystems driver is oss, you can skip this step

//fetch all files of specified bucket(see upond configuration)
Storage::files($directory);
Storage::allFiles($directory);

Storage::put('path/to/file/file.jpg', $contents); //first parameter is the target file path, second paramter is file content
Storage::putFile('path/to/file/file.jpg', 'local/path/to/local_file.jpg'); //新增接口,根据本地路径上传本地文件
Storage::get('path/to/file/file.jpg'); // get the file object by path
Storage::exists('path/to/file/file.jpg'); // determine if a given file exists on the storage(OSS)
Storage::size('path/to/file/file.jpg'); // get the file size (Byte)
Storage::lastModified('path/to/file/file.jpg'); // get date of last modification

Storage::directories($directory); // Get all of the directories within a given directory
Storage::allDirectories($directory); // Get all (recursive) of the directories within a given 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'); // Prepend to a file.
Storage::append('file.log', 'Appended Text'); // Append to a file.

Storage::delete('file.jpg');
Storage::delete(['file1.jpg', 'file2.jpg']);

Storage::makeDirectory($directory); // Create a directory.
Storage::deleteDirectory($directory); // Recursively delete a directory.It will delete all files within a given directory, SO Use with caution please.

文档

更详细的 OSS 文档请移步 Aliyun OSS DOC

如果还有什么功能需要扩展可以联系我,在 github 提一个 issues,欢迎大家一起改进

详情请移步 Aliyun-oss-storage