use Obs\ObsClient;
/**
* 上传图片
* @param string $file
*/
public function uploadImgAndFile($file)
{
// 创建ObsClient实例
$obsClient = new ObsClient([
'key' => sysconfig('upload', 'huaweioss_accessKey'),
'secret' => sysconfig('upload', 'huaweioss_accessKeySecret'),
'endpoint' => sysconfig('upload', 'huaweioss_endpoint')
]);
$filename = 'upload/'.date('Y', time()).'/'. date('m', time()).'/'.date('d', time()).'/'.time().rand(1000, 9999).'.png';
$resp = $obsClient->putObject([
'Bucket' => sysconfig('upload', 'huaweioss_bucket'),//桶名
'Key' => $filename,//文件名
'SourceFile' => $file // localfile为待上传的本地文件路径,需要指定到具体的文件名
]);
if ($resp['Reason'] == 'OK') {
$url =$resp['ObjectURL'];
return $filename;
} else {
throw new ValidateException('上传失败');
}
}
/**
* 签名生成 前端上传需要
* @param string $object 文件名
* @param string $file_type 文件类型
*/
public function obsSignature(){
$object = 'upload/'.date('Y', time()).'/'. date('m', time()).'/'.date('d', time()).'/'.time().mt_rand(1000, 9999).'.png'; //文件名
$file_type = 'image/png'; //文件类型 image/jpeg
$obsClient = new ObsClient([
'key' => sysconfig('upload', 'huaweioss_accessKey'), //OBS 中的 AK
'secret' => sysconfig('upload', 'huaweioss_accessKeySecret'), //OBS 中的 SK
'endpoint' => "https://" . sysconfig('upload', 'huaweioss_endpoint'), //注意实际的终点可能不同
'signature' => 'obs',
]);
// URL有效期,3600秒
$expires = 3600;
// 上传对象
$resp = $obsClient->createPostSignature([
'Bucket' => sysconfig('upload', 'huaweioss_bucket'), //你自己的桶名(bucket)
'Key' => $object,
'Expires' => $expires,
'FormParams' => [
'x-obs-acl' => 'public-read',
'content-type' => $file_type,
]
]);
// printf($resp);
$data['Accesskeyid'] = sysconfig('upload', 'huaweioss_accessKey'); //OBS 中的AK
$data['Policy'] = $resp['Policy'];
$data['Signature'] = $resp['Signature'];
$data['Key'] = $object;
$data['ContentType'] = $file_type;
$data['huaweioss_region'] = "https://" . sysconfig('upload', 'huaweioss_region');
return json_encode($data);
}
|