【PHP】 php 解析 base64图片上传

base64 图片编码格式: 类似如下

data:image/JPG;base64,/9j/4S/+RXhpZgAATU0AKgAAAAgACwEPAAIAAAAG

php 解析代码如下:  基于tp3.2得

public function file_upload(){$base64_str = "";  //base64 图片流
        $result_base64 = $this->get_bass64_array($base64_str);

        $file_name_base64 = $result_base64['file_name'];
        $file_type = $result_base64['flie_type'];
        $upload_img = base64_decode($file_name_base64); 

        $img_file_name = 'large/';
        $img_name = uniqid().".".$file_type;
        $upload_path = C('upload_path'); // 设置附件上传根目录
        $rootPath = C('upload_img_url'). rtrim($upload_path, '/'); //设置上传全路径
        $file_path = $rootPath."/".$img_file_name.$img_name;
        $upload_result = file_put_contents($file_path, $upload_img);//保存图片,返回的是字节数 

        if(empty($upload_result) || $upload_result =='0'){
            unlink($upload_result);
            E("文件上传失败",'102');
        }
        $img_info_size = ceil(filesize($file_path)); //单位:B
        $maxSize = 5*1024*1024; // 设置附件上传大小 5M
        if($img_info_size > $maxSize){
            unlink($upload_result);
            E("文件大小超出限制:5M",'103');
        }

        $returnPath= $upload_path.$img_file_name.$img_name;
        $preview=C('img_base').$returnPath;

        $return_data = array(
            "returnPath"=>$returnPath,
            "preview"=>$preview  //预览使用
        );
        return $return_data;
    }

    //处理base64: 
    private function get_bass64_array($data_str){
        if(empty($data_str)){
            return '';
        }
        $base_array= explode(',', $data_str);
        $base_file = $base_array[1];
        $base_file_type=$this->get_between($base_array[0], "/", ";");
        $return_data = array(
            "flie_type"=>$base_file_type,
            'file_name'=>$base_file  
        );
        return $return_data;
    }

    /*
     * php截取指定两个字符之间字符串
     * */
    private function get_between($input, $start, $end) {
        $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
        return $substr;
    }

核心代码如上,可根据自己业务或者框架代码 稍作修改,即可使用

 

posted @ 2018-03-08 09:55  依然范儿特西  阅读(591)  评论(0编辑  收藏  举报