base64编码的图片上传到服务器

jerry thinkphp 2015年11月19日 收藏
使用$.post提交表格时,图片是无法上传的(除非用编辑器插件什么的,那些都比较大)。
这是一个新思路,图片转base64编码,提交上去,当然,图片不能太大,超过上传限制是不行的。
  1. function base64_upload($base64) {
  2.     $base64_image = str_replace(' ', '+', $base64);
  3.     //post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
  4.     if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
  5.         //匹配成功
  6.         if($result[2] == 'jpeg'){
  7.             $image_name = uniqid().'.jpg';
  8.             //纯粹是看jpeg不爽才替换的
  9.         }else{
  10.             $image_name = uniqid().'.'.$result[2];
  11.         }
  12.         $image_file = "./upload/test/{$image_name}";
  13.         //服务器文件存储路径
  14.         if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
  15.             return $image_name;
  16.         }else{
  17.             return false;
  18.         }
  19.     }else{
  20.         return false;
  21.     }
  22. }