【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;
    }

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

 

转载于:https://www.cnblogs.com/richerdyoung/p/8526683.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值