PHP上传方式base64图片的接收方式

preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)

匹配结果的第二个是图片的格式

file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)));

把匹配结果的第一部分干掉然后进行base64解码就可以了!

if (!empty($base64_img) && preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
            // 图片格式校验
            switch ($result[2]) {
                case 'jpeg' :
                case 'pjpeg' :
                    $ext = 'jpg';
                    break;
                case 'x-png' :
                    $ext = 'png';
                    break;
                default :
                    $ext = $result[2];
                    break;
            }
            if (!in_array($ext, ['jpg', 'bmp', 'png'])) {
                throw new \Exception('图片格式错误');
            }

            // 文件目录
            $file_path = App::getRootPath() . 'public/upload/license/' . date('Ymd') . '/';
            if (!is_dir($file_path)) {
                mkdir($file_path,0777, true);
            }

            // 新文件
            $new_name = time() . mt_rand(10000, 99999) . '.' . $ext;
            $new_file = $file_path . $new_name;

            file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)));

            //上传至OSS
            $upload_res = $this->oss_client->uploadFile($this->bucket, $new_name, $new_file);
            if (!$upload_res) {
                throw new \Exception('图片上传失败');
            }

            // 上传成功后,删除本地文件
            @unlink($new_file);

            return $upload_res['info']['url'];

        } else {
            //文件错误
            throw new \Exception('文件格式错误');
        }
}

猜你喜欢

转载自blog.csdn.net/fujian9544/article/details/111840356