本地图片转base64格式上传到服务器(php)

来源:互联网 发布:网络机顶盒多少钱一个 编辑:程序博客网 时间:2024/05/16 12:04

选择了图片之后,js会先把已选的图片转化为base64格式,然后通过ajax上传到服务器端,服务器端再转化为图片,进行储存的一个过程。

html部分

<input type="file" id="imagesfile">

js部分

$("#imagesfile").change(function (){              var file = this.files[0];    //用size属性判断文件大小不能超过5M ,前端直接判断的好处,免去服务器的压力。    if( file.size > 5*1024*1024 ){       alert( "文件太大!" )    }    //base64    var reader=new FileReader();    reader.onload = function(){       // 通过 reader.result 来访问生成的 base64 DataURL       var base64 = reader.result;       //打印到控制台,按F12查看       console.log(base64);       //上传图片       base64_uploading(base64);      }    reader.readAsDataURL(file);            });//AJAX上传base64function base64_uploading(base64Data){    $.ajax({       type: 'POST',       url: "上传接口路径",       data: {         'base64': base64Data       },       dataType: 'json',       timeout: 50000,       success: function(data){            console.log(data);           },       complete:function() {},       error: function(xhr, type){          alert('上传超时啦,再试试');              }     });}
使用了new FileReader();的接口来转化图片,new FileReader();还有其他的接口,自行搜索。

接下来,那就是服务器端的代码了,上面的demo,是用thinkphp为框架编写的,但其他框架也基本通用的。

function base64imgsave($img){        //文件夹日期        $ymd = date("Ymd");         //图片路径地址           $basedir = 'upload/base64/'.$ymd.'';        $fullpath = $basedir;        if(!is_dir($fullpath)){            mkdir($fullpath,0777,true);        }        $types = empty($types)? array('jpg', 'gif', 'png', 'jpeg'):$types;               $img = str_replace(array('_','-'), array('/','+'), $img);               $b64img = substr($img, 0,100);        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $b64img, $matches)){        $type = $matches[2];        if(!in_array($type, $types)){            return array('status'=>1,'info'=>'图片格式不正确,只支持 jpg、gif、png、jpeg哦!','url'=>'');        }        $img = str_replace($matches[1], '', $img);        $img = base64_decode($img);        $photo = '/'.md5(date('YmdHis').rand(1000, 9999)).'.'.$type;        file_put_contents($fullpath.$photo, $img);            $ary['status'] = 1;            $ary['info'] = '保存图片成功';            $ary['url'] = $basedir.$photo;            return $ary;        }            $ary['status'] = 0;            $ary['info'] = '请选择要上传的图片';            return $ary;    }
以上就是PHP代码,原理也很简单,拿到接口上传的base64,然后再转为图片再储存。
转载请注明 原文链接:http://www.bcty365.com/content-10-5280-1.html

原创粉丝点击