js ajax上传图片到服务器

    $("#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