yii2 下base64 上传图片小例子(和yii2没什么关系)

前端上传图片前转为base64编码,拿到后解码进行存储,整个过程还是很简单的,代码中有yii2的影子,如果不需要删了就可以了,最近太懒了,就不整理了,其实也是在网上抄的 …. !-!

public function actionMemberCenter()
{
        header('Content-type:text/html;charset=utf-8'); 
        $base64_image_content       = \Yii::$app->request->post('headpic',null);
        if(!$base64_image_content) return ['code'=>404,'msg'=>'数据不能为空',data=>null];
        $api_url           =        \Yii::$app->params['api_url'];
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = "./img/lvyou/headpic/".date('Ymd',time())."/";
            if(!file_exists($new_file))
            {
                //检查是否有该文件夹,如果没有就创建,并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file.time().".{$type}";
            // base64解码后保存图片
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                $img_url = $api_url . trim($new_file,'.' );
                // 更新用户的头像地址路径
                $member = Member::findOne($this->mid);
                $member->litpic = $img_url;
                if($member->save())
                    return ['code'=>200,'msg'=>'头像保存成功','data'=>['headpic'=>$img_url]];
                else
                    return ['code'=>4042,'msg'=>'头像保存失败','data'=>['headpic'=>'']];
            }else
                return ['code'=>4041,'msg'=>'文件保存失败','data'=>null];
        }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值