分享OSS云环境文件上传与签名的重点代码

oss文件上传与签名

相信大家日常开发中,经常使用到云文件的上传与下载等功能,而国内常用的阿里云和华为云,laravel 自带的 Storage 默认并未进行友好支持。

刚好最近云迁移过程中的各种恶心,主要涉及上传与签名接口。特地记录下 OSS 云环境文件上传与签名的重点代码,以供参考。

相关包安装命令:

// 阿里云oss composer require aliyuncs/oss-sdk-php // 华为云obs composer require obs/esdk-obs-php

需注意包版本,是否与 php 版本适用。

.env 配置项:

# OSS相关配置 OSS_DRIVER=HW_OBS #华为OBS OSS_HW_ENDPOINT=https://obs.cn-east-3.myhuaweicloud.com OSS_HW_KEY=ME0AVBTNJTSJB2LH0EGI OSS_HW_SECRET=eCGffrwdx3Rt5QEmKbtEvruvGgg1mCUjMsnHfjWo OSS_HW_BUCKET=pub-obs-test-1 #阿里云 OSS_ENDPOINT=https://oss-cn-hangzhou.aliyuncs.com OSS_KEYID=LTAI4Ftno9DsfiVHADX73osa OSS_KEYSECRET=vo9KuqgaDN727eOOz1tDg77Egeg7wE OSS_BUCKET=xgimi-ipr

代码:

1. 接口声明

<?php namespace AppServiceOSS; interface IOSS {     /**      * 上传      *      * @param $fullFileName      * @param $filePath      * @return mixed      */     public function publicUpload($fullFileName, $filePath);     /**      * url验签、下载      *      * @param $fullFileName | 含前缀的完整url文件名      * @param $expires      |   过期时效      * @return mixed      */     public function getUrl($fullFileName, $expires);     /**      * 可替换url域名      *      * @param $url      * @return mixed      */     public function replaceUrl($url); }

2. 阿里 OSS 实现

<?php namespace AppServiceOSS; use OSSOssClient; class AliOSS implements IOSS {     private $endPoint;     private $keyId;     private $secret;     private $bucket;     private $ossClient;     private $expires = 3 * 24 * 3600;     private $aliHost = &#39;&#39;;     private $myHost = &#39;&#39;;     public function __construct()     {         $this->endPoint = env("OSS_ENDPOINT");         $this-&gt;keyId = env("OSS_KEYID");         $this-&gt;secret = env("OSS_KEYSECRET");         $this-&gt;bucket = env("OSS_BUCKET");         try {             $this-&gt;ossClient = new OssClient($this-&gt;keyId, $this-&gt;secret, $this-&gt;endPoint);         } catch (Exception $e) {         }     }     /**      * 上传      *      * @param $fullFileName      * @param $filePath      * @return mixed      * @throws Exception      */     public function publicUpload($fullFileName, $filePath)     {         return $this-&gt;ossClient-&gt;uploadFile($this-&gt;bucket, $fullFileName, $filePath);     }     /**      * url验签、下载      *      * @param $fullFileName      * @param $expires |   过期时效      * @return mixed      * @throws Exception      */     public function getUrl($fullFileName, $expires)     {         $expires = $expires ? $expires : $this-&gt;expires;         $signUrl = $this-&gt;ossClient-&gt;signUrl($this-&gt;bucket, $fullFileName, $expires);         return $signUrl;     }     /**      * 替换url域名      *      * @param $url      * @return mixed      */     public function replaceUrl($url)     {         return str_replace($this-&gt;aliHost, $this-&gt;myHost, $url);     } }

3. 华为 OBS 实现

<?php namespace AppServiceOSS; use ObsObsClient; class HuaweiOBS implements IOSS {     private $endPoint;     private $key;     private $secret;     private $bucket;     private $obsClient;     private $expires = 3 * 24 * 3600;     private $hwHost = &#39;&#39;;     private $myHost = &#39;&#39;;     public function __construct()     {         $this->endPoint = env("OSS_HW_ENDPOINT");         $this-&gt;key = env("OSS_HW_KEY");         $this-&gt;secret = env("OSS_HW_SECRET");         $this-&gt;bucket = env("OSS_HW_BUCKET");         try {             $this-&gt;obsClient = new ObsClient(['key' =&gt; $this-&gt;key, 'secret' =&gt; $this-&gt;secret, 'endpoint' =&gt; $this-&gt;endPoint]);         } catch (Exception $e) {         }     }     /**      * 上传      *      * @param $fullFileName      * @param $filePath      * @return mixed      */     public function publicUpload($fullFileName, $filePath)     {         $res = $this-&gt;obsClient-&gt;putObject([             'Bucket' =&gt; $this-&gt;bucket,             'Key' =&gt; $fullFileName,             'SourceFile' =&gt; $filePath         ]);         return $res;     }     /**      * url验签、下载      *      * @param $fullFileName      * @param $expires |   过期时效      * @return mixed      * @throws Exception      */     public function getUrl($fullFileName, $expires)     {         $expires = $expires ? $expires : $this-&gt;expires;         // 生成下载对象的带授权信息的URL         $res = $this-&gt;obsClient-&gt;createSignedUrl([             'Method' =&gt; 'GET',             'Bucket' =&gt; $this-&gt;bucket,             'Key' =&gt; $fullFileName,             'Expires' =&gt; $expires         ]);         return $res['SignedUrl'];     }     /**      * 替换url域名      *      * @param $url      * @return mixed      */     public function replaceUrl($url)     {         return str_replace($this-&gt;hwHost, $this-&gt;myHost, $url);     } }

Demo: 业务逻辑 + OSS 类

<?php namespace AppService; class UploadFile {     /**      * 文件上传 带签名访问      *      * @param        $files      * @param string $prefix      * @return array       * @throws Exception      */     public static function upload($files, $prefix = &#39;&#39;)     {         if (empty($files)) {             return [&#39;ok&#39; => false, 'message' =&gt; '请上传文件!'];         }         if (is_array($files)) {             $pics = [];             foreach ($files as $key =&gt; $file) {                 if ($file-&gt;isValid()) {                     $name = $file-&gt;getClientOriginalName();                     $fullName = OSS::getFullFileName($name, $prefix);                     $ret = OSS::publicUpload($fullName, $file, $prefix);                     if ($ret) {                         $url = OSS::getUrl($fullName);                         $url = OSS::replaceUrl($url);                         $pics[] = ['name' =&gt; $name, 'url' =&gt; $url, 'file_name' =&gt; $fullName];                     }                 } else {                     return ['ok' =&gt; false, 'message' =&gt; '无效文件!'];                 }             }             if (count($pics) &gt; 0) {                 return ['ok' =&gt; true, 'data' =&gt; $pics];             }         } else {             $name = $files-&gt;getClientOriginalName();             $fullName = OSS::getFullFileName($name, $prefix);             $ret = OSS::publicUpload($fullName, $files, $prefix);             if ($ret) {                 $url = OSS::getUrl($fullName);                 $url = OSS::replaceUrl($url);                 return ['ok' =&gt; true, 'data' =&gt; ['name' =&gt; $name, 'url' =&gt; $url, 'file_name' =&gt; $fullName]];             } else {                 return ['ok' =&gt; false, 'message' =&gt; '无效文件!'];             }         }     } }
<?php namespace AppService; use AppServiceOSSAliOSS; use AppServiceOSSHuaweiOBS; use Exception; class OSS {     const DEFAULT_DRIVER = &#39;HW_OBS&#39;;     const OSS_PREFIX = &#39;oss/&#39;;     public $OSSService;     /**      * 初始化 service      */     public function __construct()     {         if (env(&#39;OSS_DRIVER&#39;) === self::DEFAULT_DRIVER) {             $this->OSSService = new HuaweiOBS();         } else {             $this-&gt;OSSService = new AliOSS();         }     }     public static function getInstance()     {         return new self();     }     /**      * 使用外网上传文件      *      * @param $fullName      * @param $filePath      * @param $prefix      * @return mixed      * @throws Exception      */     public static function publicUpload($fullName, $filePath, $prefix)     {         return self::getInstance()-&gt;OSSService-&gt;publicUpload($fullName, $filePath);     }     /**      * 获取oss图片url      *      * @param $fullName      * @param $expires |    过期时效      * @return string      * @throws Exception      */     public static function getUrl($fullName, $expires = '')     {         return self::getInstance()-&gt;OSSService-&gt;getUrl($fullName, $expires);     }     /**      * 替换url域名      *      * @param $url      * @return mixed      */     public static function replaceUrl($url)     {         return self::getInstance()-&gt;OSSService-&gt;replaceUrl($url);     }     /**      * 获取完整的文件名含路径      *      * @param $fileName      * @param $prefix      * @return string      */     public static function getFullFileName($fileName, $prefix)     {         return self::OSS_PREFIX . $prefix . self::setFileName($fileName);     }     /**      * 设置新的文件名(重命名规则)      *      * @param $fileName      * @return string      */     public static function setFileName($fileName)     {         $nameArray = explode('.', $fileName);         $extension = $nameArray[count($nameArray) - 1];         $newName = date('Ymd') . '/' . date('YmdHis') . rand(10000, 99999) . '.' . $extension;         return $newName;     } }

有时间可以对其进行功能接口补充,丰富更多云接口能力。

附:

composer 包:https://packagist.org/packages/league/flysystem

composer require league/flysystem

spring mvn 包:https://spring-file-storage.xuyanwu.cn/#/ | https://spring-file-storage.xuyanwu.cn/#/

推荐学习:《laravel视频教程

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享