hyperf oss/cos 文件上传扩展

更新

  1. 移除本地存储, 要存储在本地,用hf的方法就好了。

  2. 增加cos存储

  3. 增加put方法

  4. 改善之前的代码

扩展源码

安装

  1. composer require lyxxxh/filestore
  2. php bin/hyperf.php vendor:publish lyxxxh/filestore // 发布配置
  3. 配置config/autoload/filestore.php //配置oss
    'oss' => [
         'appid' => '',
         'appsec' => '',
         'bucket' => '',
         'endpoint' => '',
         'socket_timeout' => '5184000', // 设置Socket层传输数据的超时时间
         'connection_timeout' => '10', //建立链接的超时时间
         'save_path' => 'tem/storage/',  //存储目录
    ]

控制器使用

use Xxh\FileStore\Service\FileStoreAbstract;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;/**
* 文件管理
* @Inject
* @var FileStoreAbstract
*/
private $file;//接收文件上传
public function filestore(RequestInterface $request, ResponseInterface $response)
{
    $path = $this->file->store(
     $request->file('img')
    );
    return $this->file->url($path);    
    //http://r-card.oss-cn-beijing.aliyuncs.com/tem/storage/4b7dd3231926a340ab84d53316f17e03.png?OSSAccessKeyId=LTAI4T18SS9GCtpf&Expires=1585834537&Signature=V7OSZEQaWGSG3eYgHUXmXNwTSKQ%3D
}public function put()
{
    $path = $this->file->put('1.txt','Hello World');
    return $this->file->url($path);
          //http://r-card.oss-cn-beijing.aliyuncs.com/tem/storage/1.txt?OSSAccessKeyId=LTAI4T18SS9GCtpf&Expires=1585834478&Signature=3%2FOi1YB1ggMIet%2F03Q0AnNJ4Aus%3D

}

使用cos

  1. 新增config/autoload/dependencies.php配置
    Xxh\FileStore\Service\FileStoreAbstract::class => Xxh\FileStore\Service\CosFileStoreService::class 
  2. 配置config/autoload/filestore.phpcos的信息

扩展方法 或者 重写 (以oss为例)

  1. 随便创建一个文件 例:app/Services/OssFileStoreService.php

  2. 修改config/autoload/dependencies.php

    Xxh\FileStore\Service\FileStoreAbstract::class => App\Services\OssFileStoreService::class
  3. OssFileStoreService.php内容

class OssFileStoreService extends Xxh\FileStore\Service\OssFileStoreService
{
//重写oss put方法
public function put($filename,$str)
{
    ..... 
}

//新增oss delObject方法  
public function delObject($filename) 
{ 
    $this->getClient()->deleteObjects($this->config['bucket'],$filename);  
}

}

扩展提供的方法

FileStoreAbstract.php

超过2m无法上传

默认只能上传2M的文件,
请看swoole文档 (package_max_length)

可在config/server.php的

settings =>[
    'package_max_length' => 5 * 1024 * 1024 , //5M
    .....
]
本作品采用《CC 协议》,转载必须注明作者和本文链接
专心学习不瞎搞
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
87
粉丝
105
喜欢
480
收藏
717
排名:109
访问:8.7 万
私信
所有博文
社区赞助商