天天看点

PHP 写 APP 上传图片接口

//上传头像
    public function upHeadImage(){
        $base64_img = trim($_POST['img']);//img前台将图片转为base64  post  过来
        $userID = $_POST['uid'];
        // echo  $base64_img;
        $up_dir = './uploads/images/userphoto/';//存放在当前目录的upload文件夹下
        //判断是否存在此文件夹
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777);//进行文件创建
        }
        //匹配出图片的格式
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.date('YmdHis_').'.'.$type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    //图片路径
                    $img_path = str_replace('../../..', '', $new_file);
                    $sql = "UPDATE userInfo set url='{$img_path}' where userID='{$userID}'";
                    $res = $this->db->query($sql);
                    $cnt = $res->rowCount();
                    //根据不同的返回结果,对其进行相应的响应
                    if ($cnt >= 1) {
                        Response::json(203,"头像上传成功",$img_path);
                        exit;
                    } elseif ($res == false) {
                        Response::json(407,"头像上传失败",$res);
                    } else {
                        Response::json(500,"未知错误",$res);
                    }
                }else{
                           Response::json(407,"头像上传失败");
                }
            }else{
                    //文件类型错误
                    Response::json(404,"头像上传类型错误");
            }
        }else{
            //文件错误
            Response::json(404,"头像文件错误");
        }

    }
           

问题:

前台将图片转为base64  POST  过来,在服务端输出接收的POST数据 与图片转码后的数据对比 结果发现 图片转成base64后有“+”, 但是接收的数据中“+”变成了“ ”;

解决方法:

1.     //前台先对base64格式的图片进行编码,再进行解码,传到后台的数据必须是解码后的数据

       //  var urlEncode = encodeURIComponent(imgData);

        var decode = decodeURIComponent(imgData);

2.    可在PHP接口出对POST过来的base64进行处理,将“ ”替换为“+”

        $base64_img = str_replace(" ","+",$base64_img);

//指定允许其他域名访问

header('Access-Control-Allow-Origin:*');

//设置时区

date_default_timezone_set('Asia/shanghai');

继续阅读