很多項(xiàng)目經(jīng)常會(huì)用到阿里云的OSS,每次都需要集成一遍oss的sdk。
那么有沒有一勞永逸的方法呢。答案當(dāng)然是yes!
我們可以將oss上傳做成一個(gè)可以對(duì)外提供的服務(wù),以后再需要使用的時(shí)候就直接調(diào)用就好了。
本服務(wù)采用RESTFull接口設(shè)計(jì)。
提供兩個(gè)方法:upload,urlsign
upload為統(tǒng)一上傳接口,通過這個(gè)接口可以上傳任意文件到OSS。
urlsign為url簽名接口,通過這個(gè)接口可以拿到私有bucket的簽名地址。
下面直接來看代碼
/**
* 驗(yàn)證來源ID
*/
private function checkSource() {
if (empty($GLOBALS['sources']) || empty($this->_sourceid)) {
Output::jsonStr(Error::ERROR_AUTH_SOURCE_FAIL);
}
foreach($GLOBALS['sources'] as $key => $value) {
if ($value['sourceid'] == $this->_sourceid) {
$this->_bucket = $value['bucket'];
$this->_domain = $value['domain'];
$this->_project = $key;
}
}
if (empty($this->_bucket)) {
Output::jsonStr(Error::ERROR_AUTH_SOURCE_FAIL);
}
}
這樣可能看不懂,再來看下配置

配置
這回是不是理解了呢。
通過這段代碼可以實(shí)現(xiàn)在配置里指定單獨(dú)的Bucket和綁定的域名。
但是,實(shí)際情況是如果綁定的域名是CDN域名,那么就無法操作oss了,那么有什么解決辦法呢。
答案就是:所有的上傳操作都走oss的內(nèi)網(wǎng)域名,上傳成功之后返回的地址走綁定域名。
代碼如下:
/**
* 初始化ossClient
* @param type $useDomain
* @return OssClient
*/
public function ossClient($useDomain = 0) {
$endpoint = self::endPoint;
$isCName = 0;
if($useDomain && $this->_domain){
$endpoint = $this->_domain;
$isCName = 1;
}
try {
return new OssClient(self::accessKeyId, self::accessKeySecret, $endpoint, $isCName);
} catch (OssException $e) {
Output::jsonStr(Error::ERROR_SYSTEM_FAIL, $e->getMessage());
}
}
因?yàn)橥粋€(gè)方法中不一定使用綁定的域名還是原始域名,所以這里封裝了一個(gè)方法,目的就是可以指定使用綁定的域名或者不使用。
下面就是具體的接口代碼
/**
* 統(tǒng)一上傳服務(wù)
* @param type $file_content
* @param type $save_name
* @param type $save_path
*/
public function _upload($file_content, $save_name, $save_path) {
//獲取文件類型
$type = Tools::getFileType($file_content);
if(!$type){
Output::jsonStr(Error::ERROR_PARAM_INVALID, 'unknow type.');
}
//獲取目標(biāo)文件名
$filename = $this->_getSaveName($save_name, $type);
$object = ($save_path) ? "$this->_project/$save_path/$filename" : "$this->_project/$filename";
try {
$this->ossClient()->putObject($this->_bucket, $object, $file_content);
} catch (Exception $exc) {
Output::jsonStr(Error::ERROR_SYSTEM_FAIL, $exc->getMessage());
}
$data = ['object' => $object, 'url' => $this->_getUrl($object)];
$img_info = OssPictureModel::info($this->url);
Output::jsonStr(Error::SUCCESS, $img_info ? array_merge($data, $img_info) : $data);
}
/**
* API:獲取私有Bucket中Object的signUrl
*/
public function urlSignAction() {
$object = $this->input_post_param('object');
$timeout = $this->input_post_param('timeout', 60);
if(!$object){
Output::jsonStr(Error::ERROR_PARAM_MISS);
}
try {
$this->ossClient()->doesObjectExist($this->_bucket, $object);
} catch (Exception $exc) {
Output::jsonStr(Error::ERROR_PARAM_INVALID, $exc->getMessage());
}
try {
$sign_url = $this->ossClient(1)->signUrl($this->_bucket, $object, $timeout);
} catch (Exception $exc) {
Output::jsonStr(Error::ERROR_PARAM_INVALID, $exc->getMessage());
}
Output::jsonStr(Error::SUCCESS, $sign_url);}
到這里,我們就搭建好了一個(gè)基本的服務(wù),以后有需要用到oss上傳的項(xiàng)目,只要在本服務(wù)配置文件的sources數(shù)組中新增一個(gè)成員,然后就可以通過接口直接調(diào)用了。
我是閆大伯,一只永不停歇的野生程序猿