PHP 解析 base64 图片上传 代码示例

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

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

 

php 解析代码如下 (基于Thinkphp3.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;
    }

 

base64

    A+
发布日期:2018年03月08日 18:22:28  所属分类:PHP
最后更新时间:2018-03-08 18:27:04
头像
  • ¥ 39.0元
  • 市场价:39.0元
  • ¥ 69.0元
  • 市场价:69.0元
  • ¥ 79.0元
  • 市场价:99.0元
  • ¥ 0.0元
  • 市场价:199.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: