TP5 base64图片上传



      $img = $this->baseimg_upload($param['cover'], 'Uploads');    这里tp3 没写参2可以    写参2  空字符串  都不行 创建不了文件
/*
 * 上传方法
 * */
namespace app\common\model;

use app\common\language\Chinese;
use think\Model;

class Uploads extends Model
{
    /**
     * 上传图片
     */
    public function uploadImg($file){

        /*if(empty($file))
        {
            return callback(0,'参数错误');
        }*/
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file -> move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $res = $info -> getSaveName();
            $res = str_replace('\\', '/', $res);
            $savename = "/uploads/".$res;
            return callback(1,$savename);
        }else{
            // 上传失败获取错误信息
            return callback(0,Chinese::$upload_failed,'',$info);
        }
    }

    /**
     * base64 上传图片
     * @param string $base64_img 图片base64编码
     * @param string $path 根目录
     * @param string $savepath 保存位置
     * @return array
     * */
    function baseimg_upload($base64_img, $path, $savepath){
      //$base64_img ='data:image/jpg;base64,'.str_replace('', '+', $base64_img);
       $base64_img = str_replace('', '+', $base64_img);
        $up_dir = $path.'/'.$savepath.'/'.date('Y-m-d',time());
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777,true);
        }

        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'))){
                $randStr = str_shuffle('1234567890'); //随机字符串
                $rand = substr($randStr,0,4); // 返回前四位
                $new_file = $up_dir.'/'.date('YmdHis').$rand.'.'.$type;  //完整路径 + 图片名

                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = str_replace($new_file);
                    $filename['url'] = 'https://'.$_SERVER['HTTP_HOST'].'/'. $new_file;
                    $filename['key'] = '/'.$new_file;
                    return ['status' => 1, 'msg' => "图片上传成功", 'data' => $filename];
                }
                //上传失败
                return ['status' => 2, 'msg' => "图片上传失败"];
            }
            //文件类型错误
            return ['status' => 4, 'msg' => "文件类型错误"];
        }
        //文件错误
        return ['status' => 3, 'msg' => "文件错误"];
    }
}

你可能感兴趣的:(php,tp5)