Coder Social home page Coder Social logo

jacobcyl / aliyun-oss-storage Goto Github PK

View Code? Open in Web Editor NEW
522.0 16.0 161.0 61 KB

阿里云OSS laravel storage Filesystem adapter, 打造Laravel最好的OSS Storage扩展.

Home Page: http://jacobcyl.github.io/Aliyun-oss-storage/

License: MIT License

PHP 100.00%

aliyun-oss-storage's Introduction

Aliyun-oss-storage for Laravel 5+

Aliyun oss filesystem storage adapter for laravel 5. You can use Aliyun OSS just like laravel Storage as usual.
借鉴了一些优秀的代码,综合各方,同时做了更多优化,将会添加更多完善的接口和插件,打造Laravel最好的OSS Storage扩展

Inspired By

Require

  • Laravel 5+
  • cURL extension

##Installation In order to install AliOSS-storage, just add

"jacobcyl/ali-oss-storage": "^2.1"

to your composer.json. Then run composer install or composer update.
Or you can simply run below command to install:

"composer require jacobcyl/ali-oss-storage:^2.1"

Then in your config/app.php add this line to providers array:

Jacobcyl\AliOSS\AliOssServiceProvider::class,

Configuration

Add the following in app/filesystems.php:

'disks'=>[
    ...
    'oss' => [
            'driver'        => 'oss',
            'access_id'     => '<Your Aliyun OSS AccessKeyId>',
            'access_key'    => '<Your Aliyun OSS AccessKeySecret>',
            'bucket'        => '<OSS bucket name>',
            'endpoint'      => '<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'           => <true|false> // true to use 'https://' and false to use 'http://'. default is false,
            'isCName'       => <true|false> // 是否使用自定义域名,true: 则Storage.url()会使用自定义的cdn或域名生成文件url, false: 则使用外部节点生成url
            'debug'         => <true|false>
    ],
    ...
]

Then set the default driver in app/filesystems.php:

'default' => 'oss',

Ok, well! You are finish to configure. Just feel free to use Aliyun OSS like Storage!

Usage

See Larave doc for Storage Or you can learn here:

First you must use Storage facade

use Illuminate\Support\Facades\Storage;

Then You can use all APIs of laravel 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'); // upload file from local path

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.

// upgrade logs
// new plugin for v2.0 version
Storage::putRemoteFile('target/path/to/file/jacob.jpg', 'http://example.com/jacob.jpg'); //upload remote file to storage by remote url
// new function for v2.0.1 version
Storage::url('path/to/img.jpg') // get the file url

Documentation

More development detail see Aliyun OSS DOC

License

Source code is release under MIT license. Read LICENSE file for more information.

aliyun-oss-storage's People

Contributors

chuangbo avatar darkicerain avatar jacobcyl avatar jyj1993126 avatar kerry-6 avatar xsilen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aliyun-oss-storage's Issues

rewind() expects parameter 1 to be resource, string given

AliOssAdapter : 428

    /**
     * {@inheritdoc}
     */
    public function readStream($path)
    {
        $result = $this->readObject($path);
        $result['stream'] = $result['raw_contents'];
        rewind($result['stream']);
        // Ensure the EntityBody object destruction doesn't close the stream
        $result['raw_contents']->detachStream();
        unset($result['raw_contents']);

        return $result;
    }

其中 raw_contents 是 string

isCName设置为true后上传错误

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

$filePath

public function getUrl( $path ) { if (!$this->has($path)) throw new FileNotFoundException($filePath.' not found'); return ( $this->ssl ? 'https://' : 'http://' ) . ( $this->isCname ? ( $this->cdnDomain == '' ? $this->endpoint : $this->cdnDomain ) : $this->bucket . '.' . $this->endPoint ) . '/' . ltrim($path, '/'); }

内网节点的问题

OssException in OssClient.php line 2187:
RequestCoreException: cURL resource: Resource id #438; cURL error: Failed to connect to xxx-internal.aliyuncs.com port 80: Connection timed out (7)

ErrorException: Undefined index: debug

按照文档安装了package后,使用\Storage::disk('oss')后,报错。

[ErrorException]
Undefined index: debug

不知道这是怎么一回事?谢谢了

能否新建一个直接抛出异常的Tag?

作者你好,我们在项目中使用你的代码,但方法只返回了true和false,错误的时候记录日志(我们项目是分布式的,本机日志不太适应),我们需要在失败的时候知道错误详情,是否能在方法中直接将异常抛出呢?新建一个Tag给我们使用,不胜感激!

为adaptor新增signUrl方法

为adaptor新增signUrl方法, 以便生成带签名的地址。我目前的做法是继承你的adaptor, 新增

public function signUrl($path, $timeout = 60, $method = OssClient::OSS_HTTP_GET, $options = NULL) {
	return $this->client->signUrl($this->bucket, $path, $timeout, $method, $options);
}

方法, 然后重写provider, 用自己的adaptor。

oss配置CDN失败

我修改配置如下之后网站就挂了:
'cdnDomain' => ‘my_cdn_domain',
'isCName' => true,

oss的CDN在ali上已经配好了,请问这里要怎么做呢?

建议添加内网Endpoint上传功能

建议添加ECS访问的内网Endpoint,如果设置内网Endpoint,则由内网Endpoint(oss-cn-hangzhou-internal.aliyuncs.com)上传,外网Endpoint(oss-cn-hangzhou.aliyuncs.com)下载。如果未添加内网Endpoint,全部由外网Endpoint上传、下载。

使用某些方法很繁琐


getAdapter()->getClient()->setTimeout(0);

建议用魔术方法驱动,然后注释method以便IDE提示

获取的数据异常

使用Storage::('oss')->get($path)时不时的会返回异常数据,当我获取文件内容时。有时候正常,有时候不正常。
异常数据:

<script language="javascript">setTimeout("location.replace(location.href.split(\"#\")[0])",2000);</script> <script type="text/javascript" src="http://1.1.1.3:89/cookie/flash.js"></script> <script language="javascript">setURL("1.1.1.3");supFlash("18446744069766193171");</script>

ErrorException In AliOssAdapter.php line 570

image

public function getUrl( $path )
{
if (!$this->has($path)) throw new FileNotFoundException($filePath.' not found'); //这句报错了,FileNotFoundException没有找到 2$filePath 没有定义
return ( $this->ssl ? 'https://' : 'http://' ) . ( $this->isCname ? ( $this->cdnDomain == '' ? $this->endPoint : $this->cdnDomain ) : $this->bucket . '.' . $this->endPoint ) . '/' . ltrim($path, '/');
}

建议不要捕获错误

在大多数能引发OssException的地方,都被Catch,然后简单的return false了。
但是这样在项目运行时,可能会引发一些潜在问题。

另外:在listContents方法中,调用了listDirObjects,但是当listDirObjects发生错误时,没有做异常判定。导致异常抛出。

不捕获OssException是不是更好一些?

isCName 不易作为判断是否启用CDN的依据

比如以下情况:
OSS只绑定了一个域名(且开启CDN), 这时候如果开启isCName, 则endpoint必须填写为 cname域名, 否则上传出错,
而endpoint填写为 cname域名, 会导致上传也走cdn,

Resolving timed out

Previously was fine but today when I'm tried to upload / delete, I receive this type of error:

OSS\Core\OssException: RequestCoreException: cURL resource: Resource id #393; cURL error: Resolving timed out after 10531 milliseconds (28) in /var/www/monsterpress/vendor/aliyuncs/oss-sdk-php/src/OSS/OssClient.php:2187

validateBucket 是不是有问题

/**
* 检验bucket名称是否合法
* bucket的命名规范:
* 1. 只能包括小写字母,数字

bucket是有‘-’和‘/’的,这个验证是不是有问题

ssl的配置无效(从request取也不合理)

在配置项中,有
ssl = true/false 的配置
但是在实际代码中(AliOssServiceProvider:42),是从$app['request']->secure()获取的。

这在正式环境是理论上是没有问题的。
但是在开发环境下,可能会出现问题,因为CDN设置很可能只接受https请求。
但是开发环境往往又只是http请求。

为什么无法访问 AliOssAdapter 里的方法呢?

在我的 ImageController 里,使用如下代码的时候

$url = Storage::getUrl($path);
dd($url);

得到了一个错误的提示

Call to undefined method League\Flysystem\Filesystem::getUrl

AliOssAdapter 有些方法可以访问,有些却不行。

比如我将 AliOssAdapter 里的方法 getSize($path) 改写为如下

public function getSize($path)
{
    return $path;
}

然后在我的 ImageController 里

$url = Storage::getSize($path);
dd($url);

然后又能够 dd,这就说明使用 getSize 方法的时候,已经进入了 AliOssAdapter 的 getSize 方法。
那为什么AliOssAdapter 的 getUrl 方法却无法使用呢?

支持laravel5.3吗

在laravel5.3中使用时putFile方法时会报错。
下面是5.3中FilesystemAdapter.php中putFile方法
public function putFile($path, $file, $visibility = null) { return $this->putFileAs($path, $file, $file->hashName(), $visibility); }
其中第二个参数是UploadedFile类型,而文档中写的是传string类型

cURL error

OssException In OssClient.php line 1994 :

RequestCoreException: cURL resource: Resource id #350; cURL error: Connection timed out after 10073 milliseconds (28)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.