首页 > Web开发 > 详细

js ajax上传图片到服务器

时间:2016-01-23 18:06:34      阅读:337      评论:0      收藏:0      [点我收藏+]
    $("#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)));

 

js ajax上传图片到服务器

原文:http://www.cnblogs.com/jh1994/p/5153656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!