zoukankan      html  css  js  c++  java
  • 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)));
  • 相关阅读:
    coolSQL安装与使用
    测试经验--测试流程总结
    测试经验--测试用例结构设计
    python 爬虫与数据可视化--数据提取与存储
    python 爬虫与数据可视化--爬虫基础知识
    在Eclipse中用TODO标签管理任务(Task)
    Web性能优化:图片优化
    Firebug入门指南
    Git远程操作详解
    Firebug控制台详解
  • 原文地址:https://www.cnblogs.com/jh1994/p/5153656.html
Copyright © 2011-2022 走看看