记一次简单且完整的图片上传

终于完成一次完整图片上传功能!

直接上代码!!

样式

<style>
      li {
        list-style: none;
        cursor: pointer;
      }
      #doImg {
        width: 100px;
        height: 100px;
        float: left;
        display: none;
      }
      .spanColor {
        display: block;
        margin-top: 3px;
        text-align: center;
        height: 18px;
      }
      #addButton {
        width: 100px;
        height: 100px;
        color: #ddd;
        border: 2px solid #ddd;
        text-align: center;
    }
    </style>

 

内容代码如下:

<li id="Identification_img">
      <!-- 图片框 -->
        <div id="doImg">
            <img id="imgPlace"  src=''  style="display: block;margin: 0px auto;" height="100px"/>
                <span class="span spanColor" style="display: block;margin-top: 3px;text-align: center;height: 18px;">
                    <input type="file" name="IdentificationImg" id="replace_img" style="display: none;"  onchange="discern_img.photoUpload(this)" accept="image/png,image/jpeg"  class="basic_prop">
                    <label for="replace_img">
                        <span title="替换" class="fa fa-image" style="margin-right: 10px;color: blue;cursor: pointer;">替换</span>
                    </label>
                    <a title="删除" href="javascript:void(0);" class="fa fa-times" onclick="discern_img.deleteImg()">删除
                    </a>
                </span>
        </div>
        <!-- 添加按钮 -->
        <div id="addButton">
            <input type="file" name="IdentificationImg" id="add_img" style="display: none;" onchange="discern_img.photoUpload(this)" class="basic_prop">
            <label for="add_img" style="margin-bottom: 0">
                <span class="fa fa-plus imgAdd" style="line-height: 98px;"></span>
                <span style="line-height: normal;">图片上传</span>
            </label>
        </div>
        <div id="waitAlert" style="float:left;margin-top:40px;"></div>
    </li>

最后是脚本代码:

<script src="./js/jquery-2.1.4.min.js"></script>
  <script>
    var discern_img = {
    photoUpload: function (file) {
            // Get a reference to the fileList
            var files = !!file.files ? file.files : [];
            // If no files were selected, or no FileReader support, return
            if(!files.length || !window.FileReader) return;
            // 不是图片格式或jpg/png
            if(files[0].type.split("/")[0] !== "image" || files[0].type.split("/")[1] !== "jpeg" && files[0].type.split("/")[1] !== "png") {
                alert("请选择正确的图片格式!");
                return;
            }
            img_type = files[0].type; // 获取图片格式
            var name=files[0].name;//获取图片名称
            // Create a new instance of the FileReader
            var reader = new FileReader(files[0]);
            var img_attr = $("#imgPlace"); // 为了改图片属性

            // 加载图片
            reader.onload = function () {
                var result=this.result;
                $('#submit-btn').attr("disabled","disabled");
                $("#waitAlert").html('<img src="/img/loading1.gif" align="absmiddle">');

                $("#doImg").css({'display':'block'});
                $("#addButton").css({'display':'none'});
                img_attr.attr("src", result);
            };

            // 因为这里图片太大会被卡一下,整个页面会不可操作,页面整体虚化
            if(files[0].size > 1024 * 1024) {
                $("body").css("opacity", 0.5);
            }

            // Read the local file as a DataURL
            reader.readAsDataURL(files[0]);
            // When loaded, set image data as background of div
            // 加载图片完成
            reader.onloadend = function() {
                var img_attr = $("#imgPlace");
                var width = img_attr[0].naturalWidth,height = img_attr[0].naturalHeight;
                var cvs = document.createElement('canvas');
                var ctx = cvs.getContext("2d"); // 新建画布
                cvs.width = width; cvs.height = height;
                ctx.drawImage(img_attr[0],0,0,width,height,0,0,width,height);
                var img_type = files[0].type;
                var quality=0.93;
                var size=files[0].size;
                if(1*1024*1024<size && size<2*1024*1024){
                    quality=0.7;
                }else if(2*1024*1024<=size && size<4*1024*1024){
                    quality=0.5;
                }else if(size>=4*1024*1024){
                    quality=1;
                }
                // 导出图片为base64格数
                result_img = cvs.toDataURL(img_type, quality);
                var formData = new FormData();
                formData.append("file",result_img);
                $.ajax({
                    type: "post",
                    url: '接口路径',
                    data: formData,//要传给后台的图片数据
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    success: function (data) {//上传成功后的回调函数
                        var url=data.data.url;
                        img_attr.attr("src",url);
                        $("#waitAlert").html('<img src="/img/file_upload_ok.gif" align="absmiddle">');
                        $('#submit-btn').removeAttr("disabled");
                    },
                    error:function(e){
                        alert('网络错误');
                        $("#waitAlert").html('<img src="/img/file_upload_ok.gif" align="absmiddle">');
                        $('#submit-btn').removeAttr("disabled");
                    }
                });
                // 页面还原
                if(files[0].size > 1024 * 1024) {
                    $("body").css("opacity", 1);
                }
            };
        },
        // 删除功能
        deleteImg: function () {
            $("#doImg").css({'display':'none'});
            $("#doImg").find('img').attr('src','');
            $("#addButton").css({'display':'block'});
            $("#waitAlert").html('');
        }

      }
  </script>

图片上传了解一下?

 

posted @ 2018-04-24 12:05  思绪在漫游  阅读(525)  评论(0编辑  收藏  举报