OSS对象存储
/**
* +------------------------------------------------------------------------------
* UserController
* +------------------------------------------------------------------------------
* time 2018/12/25
* @description uploadOperController
* +------------------------------------------------------------------------------
*/
namespace Home\Controller;
class UploadOperController extends CommonController
{
public function __construct()
{
parent::__construct();
}
/**
* OSS直接上传
* $path 上传文件的绝对路径$path="E:\phpstudy\phpstudy\WWW/newShop\pc_api_lishe_cn\product/1.jpg"
* $type 规定好eg:goodsImage temp(默认临时目录)
*/
public function aiuploadPathByOss_in($path="",$type="temp"){
$resultArray = array(
"errcode" => 0,
"msg" => "",
);
$allowTypes = ["idCardImage","goodsImage","temp"];
if(!in_array($type, $allowTypes)){
$resultArray["errcode"] = 1;
$resultArray['msg'] = '类型不符合规范';
return $resultArray;
}
vendor('OSS.autoload');
// 阿里云主账号AccessKey
$accessKeyId = "";
$accessKeySecret = "";
// Endpoint以杭州为例,其它Region请按实际情况填写。
$endpoint = "";
// 存储空间名称
$bucket= "lishe-shop-images";
if(!$path){
$resultArray["errcode"] = 1;
$resultArray['msg'] = '文件路径不能为空!';
return $resultArray;
}
// 文件名称
$ext = pathinfo($path)['basename'];
$time = time();
$subType=date('Y-m-d',$time)."/".$time."_";
$object = $type."/".$subType.$ext;
$content = $path;
$data = array();
// echo __DIR__;die;
try {
$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
$result = $ossClient->uploadFile($bucket,$object,$content);
$data['img'] = $result['info']['url'];
} catch (OssException $e) {
// print $e->getMessage();
$this->makeLog('uploadByOss', 'ErrorMessage:' . $e->getMessage() . "\r\n");
}
// return $data['img'];
$resultArray['msg'] = $data['img'];
return $resultArray;
}
/**
* OSS获取到文件再次上传
* $type 规定好eg:goodsImage temp(默认临时目录)
* 此接口不支持JSONP,此接口仅支持CORS
*/
public function aiuploadFileByOss($type="temp"){
header('Access-Control-Allow-Origin: *');
$ret=array(
'result'=>100,
'errcode'=>0,
'msg'=>"",
);
$imgArr = $_FILES;
if(!$imgArr){
$ret['errcode']=1;
$ret['msg']='请上传图片!';
$this->ajaxReturn($ret, "JSON");
exit();
}
$time = time();
$subType=date('Y-m-d',$time)."/";
$uploadDir = dirname(dirname(dirname(__FILE__)))."/Runtime/Cache/uploadImg/";
$this->mkdirs($uploadDir);
$imgArray = array();
foreach ($imgArr as $key => $value) {
move_uploaded_file($value['tmp_name'],$uploadDir.$time.'_'.$value['name']);
$movedImg = $uploadDir.$time.'_'.$value['name'];
$response = $this->aiuploadPathByOss_in($movedImg ,$type);
if($response["errcode"] != 0 ){
$ret['errcode']=1;
$ret['msg']=$response["msg"];
$this->ajaxReturn($ret, "JSON");
exit();
};
$imgArray[] = $response["msg"];
}
$ret=array(
'result'=>100,
'errcode'=>0,
'msg'=>'上传图片成功',
'data'=>array('imgurls'=> $imgArray),
);
$this->ajaxReturn($ret,"JSON");
exit();
}
private function mkdirs($dir, $mode = 0777)
{
if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
if (!mkdirs(dirname($dir), $mode)) return FALSE;
return @mkdir($dir, $mode);
}
}