您现在的位置是:网站首页> 编程资料编程资料

PHP常用函数之base64图片上传功能详解_php技巧_

2023-05-25 292人已围观

简介 PHP常用函数之base64图片上传功能详解_php技巧_

本文实例讲述了PHP常用函数之base64图片上传功能。分享给大家供大家参考,具体如下:

HTML页面代码:

PHP 处理代码:

 function upload_image($file_data){ $upload_result = array('status' => true, 'msg'=>'','err_info'=>''); if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file_data, $result)) { //处理base64字符串 $img_base64 = str_replace($result[1], '', $file_data); $img_base64 = str_replace('=', '', $img_base64); $source_img = base64_decode($img_base64); //判断文件大小 $file_size = //上传目录 $basedir = './img_test'; //后缀 $img_suffix = $result[2];//文件后缀 //文件名 // $filename = uniqid();//文件名 $filename = date('YmdHis',time());//文件名 //文件完整路径 $filepath = $basedir . "/" . $filename . "." . $img_suffix; //目录若果不存在,则创建目录 if(!is_dir($basedir)){ mkdir($basedir); chmod($basedir,0777); } //上传文件 try { file_put_contents($filepath, $img_base64); $filepath = substr($filepath, 1); $upload_result = array('status' => true, 'msg'=>'上传成功','err_info'=>'','path'=>$filepath); return $upload_result; } catch (Exception $e) { $upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>$e->getMessage()); return $upload_result; } // if (file_put_contents($filepath, base64_decode(str_replace($result[1], '', $file_data)))) { // //$size = getimagesize($filepath); // $filepath = substr($filepath, 1); // //$arr['filepath'] = $filepath; // //$arr['size'] = $size[3]; // return $filepath; // }else{ // return false; // } }else{ $upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>'请携带base64字符串的前缀'); return $upload_result; } } $res = upload_image($file_data); echo json_encode($res); 

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php文件操作总结》、《PHP目录操作技巧汇总》、《PHP常用遍历算法与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《PHP网络编程技巧总结

希望本文所述对大家PHP程序设计有所帮助。

-六神源码网