PHP下的base64图片上传

版权声明:默先森||[email protected] https://blog.csdn.net/Error_Q/article/details/90174956

吾生也有涯,而知也无涯~欢迎优化补充、指正!

(可以直接调用本方法进行使用,$imgString位base64编码后的图片信息。返回值自行添加需要的信息~)

*本文是在tp5下进行编译与调试的!其他框架同理,请自行调整~

function base64Image($imgString)
    {
        if (!empty($imgString) && preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgString, $result)) {
            $ext = $result[2];
            //生成当天日期字符串
            $today = date('Ymd', time());
            //文件上传目录
            $upload_path = 'uploads/' . $today;
            $upload_path = 'uploads/' . $today;
            if (!file_exists($upload_path)) {
                mkdir($upload_path, 0777,true);
            }
            //文件路径名
            $filename = uniqid() . '.' . $ext;
            if (file_put_contents($upload_path . '/' . $filename, base64_decode(str_replace($result[1], '', $imgString)))) {
                return '/'.$upload_path . '/' . $filename;
            } else {
                return '';
            }
        }
        return '';
    }

猜你喜欢

转载自blog.csdn.net/Error_Q/article/details/90174956