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

            $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的私我)

posted @ 2022-11-30 14:36  niniko  阅读(674)  评论(0编辑  收藏  举报