经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
PHP常用函数之base64图片上传功能详解
来源:jb51  时间:2019/10/21 12:58:34  对本文有异议

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

HTML页面代码:

  1. <html>
  2. <head>
  3. <meta charset="utf-8">
  4. </head>
  5. <body>
  6. <img id="articleImg" width="180" height="100">
  7. <input type="file" value="上传" id="articleImgBtn" />
  8. <script type="text/javascript" src = 'jquery-2.1.4.min.js'></script>
  9. <script type="text/javascript">
  10. $('#articleImgBtn').change(function(){
  11. run(this, function (data) {
  12. uploadImage(data);
  13. });
  14. });
  15. function run(input_file, get_data) {
  16. /*input_file:文件按钮对象*/
  17. /*get_data: 转换成功后执行的方法*/
  18. if (typeof (FileReader) === 'undefined') {
  19. alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
  20. } else {
  21. try {
  22. /*图片转Base64 核心代码*/
  23. var file = input_file.files[0];
  24. //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
  25. if (!/image\/\w+/.test(file.type)) {
  26. alert("请确保文件为图像类型");
  27. return false;
  28. }
  29. var reader = new FileReader();
  30. reader.onload = function () {
  31. get_data(this.result);
  32. }
  33. reader.readAsDataURL(file);
  34. } catch (e) {
  35. alert('图片转Base64出错啦!' + e.toString())
  36. }
  37. }
  38. }
  39. function uploadImage(img) {
  40. //判断是否有选择上传文件
  41. var imgPath = $("#articleImgBtn").val();
  42. if (imgPath == "") {
  43. alert("请选择上传图片!");
  44. return;
  45. }
  46. //判断上传文件的后缀名
  47. var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
  48. if (strExtension != 'jpg' && strExtension != 'gif'
  49. && strExtension != 'png' && strExtension != 'bmp') {
  50. alert("请选择图片文件");
  51. return;
  52. }
  53. $.ajax({
  54. type: "POST",
  55. url: 'http://localhost/123.php',
  56. // data: {file: img.substr(img.indexOf(',') + 1)}, //视情况将base64的前面字符串data:image/png;base64,删除
  57. data: {file: img}, //视情况将base64的前面字符串data:image/png;base64,删除
  58. cache: false,
  59. success: function(data) {
  60. var return_info = JSON.parse(data);
  61. if(return_info.status){
  62. $("#articleImg").attr('src', return_info.path);
  63. alert("上传成功");
  64. }else{
  65. alert(return_infoerr_info);
  66. }
  67. },
  68. error: function(XMLHttpRequest, textStatus, errorThrown) {
  69. alert("上传失败,请检查网络后重试");
  70. }
  71. });
  72. }
  73. </script>
  74. </body>
  75. </html>
  76.  

PHP 处理代码:

  1. function upload_image($file_data){
  2. $upload_result = array('status' => true, 'msg'=>'','err_info'=>'');
  3. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file_data, $result)) {
  4. //处理base64字符串
  5. $img_base64 = str_replace($result[1], '', $file_data);
  6. $img_base64 = str_replace('=', '', $img_base64);
  7. $source_img = base64_decode($img_base64);
  8. //判断文件大小
  9. $file_size =
  10. //上传目录
  11. $basedir = './img_test';
  12. //后缀
  13. $img_suffix = $result[2];//文件后缀
  14. //文件名
  15. // $filename = uniqid();//文件名
  16. $filename = date('YmdHis',time());//文件名
  17. //文件完整路径
  18. $filepath = $basedir . "/" . $filename . "." . $img_suffix;
  19. //目录若果不存在,则创建目录
  20. if(!is_dir($basedir)){
  21. mkdir($basedir);
  22. chmod($basedir,0777);
  23. }
  24. //上传文件
  25. try {
  26. file_put_contents($filepath, $img_base64);
  27. $filepath = substr($filepath, 1);
  28. $upload_result = array('status' => true, 'msg'=>'上传成功','err_info'=>'','path'=>$filepath);
  29. return $upload_result;
  30. } catch (Exception $e) {
  31. $upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>$e->getMessage());
  32. return $upload_result;
  33. }
  34. // if (file_put_contents($filepath, base64_decode(str_replace($result[1], '', $file_data)))) {
  35. // //$size = getimagesize($filepath);
  36. // $filepath = substr($filepath, 1);
  37. // //$arr['filepath'] = $filepath;
  38. // //$arr['size'] = $size[3];
  39. // return $filepath;
  40. // }else{
  41. // return false;
  42. // }
  43. }else{
  44. $upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>'请携带base64字符串的前缀');
  45. return $upload_result;
  46. }
  47. }
  48. $res = upload_image($file_data);
  49. echo json_encode($res);
  50.  

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

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号