js ajax上传图片到服务器

本文介绍了一种前端实现的图片上传方法,通过canvas进行图片压缩并转换为Base64编码,然后通过Ajax发送到服务器。服务端接收Base64编码的图片数据并保存。
    $("#up_goods_pic").on('change',function(){
        var file = this.files[0];
        var url = webkitURL.createObjectURL(file);
 
        /* 生成图片
        * ---------------------- */
        var $img = new Image();
        $img.onload = function() {
 
            //生成比例
            var width = $img.width,
                    height = $img.height,
                    scale = width / height;
            width = parseInt(800);
            height = parseInt(width / scale);
 
            //生成canvas
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            canvas.height = this.height;
            canvas.width = this.width;
            ctx.drawImage($img, 0, 0, width, height);
            var base64 = canvas.toDataURL('image/jpeg');
 
            //发送到服务端
            $.ajax({
                data:{
                    data:base64
                },
                url:"/shop/upload_goods_pic",
                type:"POST",
                dataType:"json",
                succeed:function(data){
                    if(data.error === 0){
                        $("#goods_pic").append("<img src='"+data.file+"'/>");
                    }else{
                        alert(data.msg);
                    }
                }
            });
            
 
        }
        $img.src = url;
 
    });

服务端

        $base64_image_content = $this->input->post("data");
        
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = "./".time().rand().".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                $this->goods_pic_model->add($new_file);
                die(json_encode(array("file"=>$new_file,"error"=>0)));
            }
        }
        
        die(json_encode(array("error"=>1)));

 

转载于:https://www.cnblogs.com/jh1994/p/5153656.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值