您的位置:首页 > 编程语言 > PHP开发

BASE64 接收图片上传到阿里云OSS

2017-12-27 16:31 1606 查看
$pic = I('post.pic');
if($pic){
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $pic, $result)){
$type = $result[2];
if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
$pic_name = time().rand(1,1000).'.'.$type;
$file = './Public/headPic/'.$pic_name;
$object = 'head-image/'.$pic_name;
if(file_put_contents($file, base64_decode(str_replace($result[1], '', $pic)))){
vendor('aliyun.autoload');
$ossClient = new \OSS\OssClient(C('accessKeyId'),C('accessKeySecret'),C('endpoint'));
try{
$getOssInfo = $ossClient->uploadFile(C('bucket'),$object,$file);
$getOssPdfUrl = $getOssInfo['info']['url'];
if($getOssPdfUrl){
unlink($file);
$data['pic'] = 'http://***/head-image/'.$pic_name;
}
}catch(OssException $e){
printf($e->getMessage() . "\n");
return;
}
}else
$this->returnResult(false,array(),'图片上传失败');
}else
$this->returnResult(false,array(),'图片类型错误');
}else
$this->returnResult(true,array(),'图片编码错误');
}

代码是搜到的 做了点修改 改成app常用的base64 传到后端

查了很多资料 不能直接上传到oss 必须经过本地这一环节 所以最后操作完把本地图unlink一下

$file 是存在本地的图片路径

$object是oss里空间下的路径

(开源中国好像不能上传文件 我的是thinkphp里写的 要sdk的私我)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息