1. 程式人生 > 其它 >BASE64 接收圖片上傳到阿里雲OSS

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