PHP上传方式base64图片的接收方式
生活随笔
收集整理的這篇文章主要介紹了
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('文件格式錯誤');} }?
總結
以上是生活随笔為你收集整理的PHP上传方式base64图片的接收方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP浏览器中的data类型的Url格式
- 下一篇: PHP与Redis结合令牌桶算法进行实现