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

选择了图片之后,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上传base64
function 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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值