1. 程式人生 > >帶裁剪的圖片上傳功能jquery外掛

帶裁剪的圖片上傳功能jquery外掛

實現圖片上傳及圖片裁剪功能,時間比較倉促,目前只允許單圖片有裁剪功能,其中圖片裁剪用到了imgareaselect外掛,其實前端是偽裁剪,將裁減座標傳遞給後臺處理,需後臺配合,備份一下程式碼
/**
 * Created by lgy on 2017/11/25.
 * 圖片上傳外掛
 */
(function ($) {
    $.fn.esupload = function (options) {
        //初始化引數
        var defaults = {
            maxfilenum: 8,
            nowfilenum: 0,
            uploadurl: "", //上傳圖片路徑
            cuturl:"",  //需裁剪的圖片地址
            mid:"",
            cutshow:false,
            width:80,
            minheight:"",
            imgSize:500,  //以k為單位
            height:"",
            uploadimgurls: [],
            showallbtn: true
        };
        var opts = $.extend(defaults, options);
        return this.each(function () {
            var $this = $(this);//獲取當前物件
            var html = '';
            if (opts.showallbtn) {
                html += '<div class="btn-upload"><span>批量上傳</span><input type="file" class="btn-upload-input" name="allpic" multiple="' + opts.maxfilenum + '" ></div>' +
                    '<span> 最多允許上傳' + opts.maxfilenum + '張圖片</span><br><br>';
            }
            html += '<div style="clear: both;">';
            if(opts.mid!=""){
                if(opts.uploadimgurls.length>0){
                    var imgurls="";
                    for(var i=0;i<opts.uploadimgurls.length;i++){
                        imgurls+=opts.uploadimgurls[i]+",";
                    }
                    imgurls=imgurls.substring(0,imgurls.length-1);
                    html +='<input id='+opts.mid+' name="'+opts.mid+'" class="upload_img_name" type="hidden" value="'+imgurls+'">';
                }else{
                    html +='<input id='+opts.mid+' name="'+opts.mid+'" class="upload_img_name" type="hidden">';
                }
            }else{
                if(opts.uploadimgurls.length>0){
                    var imgurls="";
                    for(var i=0;i<opts.uploadimgurls.length;i++){
                        imgurls+=opts.uploadimgurls[i]+",";
                    }
                    imgurls=imgurls.substring(0,imgurls.length-1);
                    html +='<input name="upload_img_name" class="upload_img_name" type="hidden" value="'+imgurls+'">';
                }else{
                    html +='<input name="upload_img_name" class="upload_img_name" type="hidden">';
                }

            }

            html +='<div class="show-upload">' +
                '<div class="s-up-div">';
            if (opts.uploadimgurls.length > 0) {
                opts.nowfilenum = opts.uploadimgurls.length;
                $.each(opts.uploadimgurls, function (i, s) {
                    html += '<div class="s-up-wcon"><div class="s-up-k">' +
                        '<p class="s-up-img"><img src="' + s + '" width="100%"></p>' +
                        '</div>'+
                        '<span class="s-up-close"></span>' +
                        '<div class="s-cut-pic">裁剪圖片</div></div>';
                });
            }
            html += '</div>';
            if (opts.uploadimgurls.length > 0 && opts.uploadimgurls.length>=opts.maxfilenum) {
                console.log("隱藏新增按鈕");
                html +='<div class="s-up-wcon s-up-add" style="display:none;"><div class="s-up-k2">' +
                    '<span class="s-add-img"></span>' +
                    '<input type="file" class="btn-upload-input" name="imgFile" >' +
                    '</div></div>';
            }else{
                html +='<div class="s-up-wcon s-up-add"><div class="s-up-k2">' +
                    '<span class="s-add-img"></span>' +
                    '<input type="file" class="btn-upload-input" name="imgFile" >' +
                    '</div></div>';
            }

            html +='</div></div>';
            //載入圖片截圖功能html
            if(opts.cutshow){
                html+='<div class="imgAreaDiv">'+
                    '<div class="img-area-mask"></div><div class="img-area-k">' +
                    '<div class="img-area-title">' +
                    '<span>圖片裁剪</span>' +
                    '<span class="img-area-close">X</span>' +
                    '</div>' +
                    '<div class="img-area-con">' +
                    '<div class="img-area-ys">' +
                    '<img class="img-before-photo-ys" style="display:none;"><img class="img-before-photo" src="">' +
                    '</div>' +
                    '<div class="img-area-cj">' +
                    '<div class="img-cj-txt">裁剪後圖片預覽</div>' +
                    '<div class="img-cj-con">' +
                    '<div class="img-after-photo img-cj-pic">' +
                    '<img src="">' +
                    '</div></div>' +
                    '</div></div>' +
                    '<div class="img-area-footer">' +
                    '<button type="button" class="img-area-pic">上傳截圖</button>' +
                    '</div></div></div>';
            }

            $this.html(html);


            if(opts.height=="auto"){
                $this.find(".s-up-k, .s-up-img").css({width:opts.width+"px",height:"auto"});
            }else{
                $this.find(".s-up-k, .s-up-img").css({width:opts.width+"px",height:opts.width+"px"});
            }
            if(opts.minheight!=""){
                $this.find(".s-up-k2").css({width:opts.minheight+"px",height:opts.minheight+"px"});
            }

            //刪除事件
            delpic();
            //監聽批量上傳事件
            $(this).find('input[name="allpic"]').on('change', function () {
                if (typeof this.files == 'undefined') {
                    return;
                }
                $.each(this.files, function (i, f) {
                    pulicupload(f);
                });
            });
            //監聽單圖片上傳事件
            $(this).find('input[name="imgFile"]').on('change', function () {
                if (typeof this.files == 'undefined') {
                    return;
                }
                pulicupload(this.files[0]);
                $(this).val("");
            });

            //上傳圖片公用方法
            function pulicupload(file) {
                if (opts.nowfilenum > opts.maxfilenum - 1) {
                    $this.find(".s-up-add").hide();
                    alert("最多隻能上傳" + opts.maxfilenum + "張圖片");
                    return;
                }
                var img = file;//獲取圖片資訊
                //console.log(img.size);
                if((img.size/1024)>opts.imgSize){
                    alert("上傳圖片不能大於" + opts.imgSize + "kb");
                    return;
                }
                //var imgtype = img.type;//獲取圖片型別,判斷使用
                var url = getObjectURL(file);//使用自定義函式,獲取圖片本地url
                var fd = new FormData();//例項化表單,提交資料使用
                fd.append('imgFile', img);//將img追加進去
                fd.append('fileName', img.name);
                var imghtml = '<div class="s-up-wcon"><div class="s-up-k"><div class="s-up-loading"><span class="s-load-tb"></span></div>' +
                    '<p class="s-up-img"><img src="' + url + '" width="100%"></p>' +
                    '</div>'+
                    '<span class="s-up-close"></span>' +
                    '<div class="s-cut-pic">裁剪圖片</div></div>';
                $this.find(".s-up-div").append(imghtml);


                //開啟截圖視窗
                $this.find(".s-cut-pic").unbind('click').click(function(){
                		$this.find(".img-cj-pic img").removeAttr("style");
                    var imgurl=$this.find(".upload_img_name").val();
                    console.log(imgurl)
                    $this.find(".img-before-photo-ys").attr("src",imgurl);
                    $this.find(".img-before-photo").attr("src",imgurl);
                    $this.find(".img-after-photo img").attr("src",imgurl);
                    $this.find(".imgAreaDiv").show();
                    $this.find('.img-before-photo').imgAreaSelect({
                        aspectRatio:"1:1",
                        handles: true,
                        autoHide:true,
                        onSelectEnd: preview
                    });
                    //截圖事件
                    function preview(img, selection) {
                        console.log(selection);
                        if (!selection.width || !selection.height)
                            return;
                        var scaleX = 150 / selection.width;
                        var scaleY = 150 / selection.height;
                        var hei = $this.find('.img-before-photo').height();
                        var wid = $this.find('.img-before-photo').width();
                        //console.log(scaleX+"|"+scaleY+"|"+hei+"|"+wid)
                        $this.find('.img-after-photo img').css({
                            width: Math.round(scaleX * wid),
                            height: Math.round(scaleY * hei),
                            marginLeft: -Math.round(scaleX * selection.x1),
                            marginTop: -Math.round(scaleY * selection.y1)
                        });
                        //上傳截圖事件
                        $this.find('.img-area-pic').unbind('click').click(function(){
                            var cm=$this.find(".img-before-photo-ys").width()/300;
                            $.ajax({
                                type: 'post',
                                url: opts.cuturl,
                                data: {
                                    srcPath:img.src,
                                    x:parseInt(selection.x1*cm),
                                    y:parseInt(selection.y1*cm),
                                    width:parseInt(selection.width*cm),
                                    height:parseInt(selection.height*cm)
                                },
                                dataType: 'json',
                                success: function (data) {
                                    console.log(data)
                                    if(data.code==1000){
                                        $this.find(".upload_img_name").val(data.datas.fileName);
                                        $this.find(".s-up-img img").attr("src",data.datas.fileName);
                                        $this.find(".imgAreaDiv").hide();
                                    }
                                }
                            })
                        });
                    }
                    //關閉截圖視窗
                    $this.find(".img-area-close").click(function(){
                        $this.find(".imgAreaDiv").hide();
                    });
                });

                if(opts.height=="auto"){
                    $this.find(".s-up-k, .s-up-img").css({width:opts.width+"px",height:"auto"});
                }else{
                    $this.find(".s-up-k, .s-up-img").css({width:opts.width+"px",height:opts.width+"px"});
                }
                if(opts.minheight!=""){
                    $this.find(".s-up-k2").css({width:opts.minheight+"px",height:opts.minheight+"px"});
                }
                //刪除事件
                delpic();
                //開始上傳圖片
                uploadpic(fd,$this.find(".s-up-wcon"));
                //上傳成功後清空檔案欄
                opts.nowfilenum = opts.nowfilenum + 1;
                if (opts.nowfilenum >= opts.maxfilenum) {
                    $this.find(".s-up-add").hide();
                }
            }

            //自定義獲取圖片路徑函式
            function getObjectURL(file) {
                var url = null;
                if (window.navigator.userAgent.indexOf("Chrome") >= -1 || window.navigator.userAgent.indexOf("Safari") >= -1) {
                    url = window.webkitURL.createObjectURL(file);
                }
                else {
                    url = window.URL.createObjectURL(file);
                }
                return url;
            }

            //刪除圖片事件
            function delpic() {
                //刪除圖片按鈕滑鼠滑過事件
                $this.find(".s-up-wcon").hover(function () {
                    $(this).find(".s-up-close").show();
                }, function () {
                    $(this).find(".s-up-close").hide();
                });
                //刪除圖片按鈕點選事件
                $this.find(".s-up-close").unbind('click').on("click", function () {
                    console.log($(this).parent().index());
                    var curindex=$(this).parent().index();
                    $(this).parent().remove();
                    opts.nowfilenum = opts.nowfilenum - 1;
                    $this.find(".s-up-add").show();
                    opts.uploadimgurls.splice(curindex,1);
                    $this.find(".upload_img_name").val(opts.uploadimgurls);
                });
            }

            //上傳圖片功能
            function uploadpic(fd,curdiv) {
                //開始ajax請求,後臺用的tp
                $.ajax({
                    type: 'post',
                    url: opts.uploadurl,
                    data: fd,
                    processData: false,  // tell jQuery not to process the data  ,這個是必須的,否則會報錯
                    contentType: false,   // tell jQuery not to set contentType
                    dataType: 'json',
                    xhr: function () {//這個是重點,獲取到原始的xhr物件,進而繫結upload.onprogress
                        var xhr = $.ajaxSettings.xhr();
                        console.log(xhr);
                        console.log(xhr.response);
                        xhr.upload.onprogress = function (ev) {
                            //這邊開始計算百分比
                            var parcent = 0;
                            if (ev.lengthComputable) {
                                percent = 100 * ev.loaded / ev.total;
                                percent = parseFloat(percent).toFixed(2);
                                console.log(percent)
                                //$('.bgpro').css('width',percent + '%').html(percent + '%');
                            }
                        };
                        return xhr;
                    },
                    success: function (data) {
                        console.log(data);
                        if(data.fileResult==1){
                            opts.uploadimgurls.push(data.fileName);
                            //$this.attr("cur_pic_url",data);
                            if(opts.cutshow && opts.maxfilenum==1){
                                curdiv.find(".s-cut-pic").show();
                            }
                            curdiv.find(".s-up-loading").hide();
                            $this.find(".upload_img_name").val(opts.uploadimgurls);
                        }else{
                            alert("上傳失敗");
                        }

                    }
                });
            }
        });
    };
})(jQuery);

css部分:

body{
    font-family: "Helvetica Neue", "Luxi Sans", "DejaVu Sans", Tahoma, "Hiragino Sans GB", STHeiti, "Microsoft YaHei";
    margin: 0;
    padding: 0;
}
p{
    padding: 0;
    margin: 0;
}
.btn-upload{
    position: relative;
    font-size: 12px;
    padding: 5px 15px;
    background-color: #2c8aec;
    display: inline-block;
    color: #fff;
}
.btn-upload-input{
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    right:0;
    bottom:0;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.controls input.btn-upload-input{
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width:100%;
    height:100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.show-upload{

}
.s-up-k{
    position: relative;
    padding: 0;
    width: 80px;
    height: 80px;
    overflow:hidden;
    background-color: #fff;
    border: 1px solid #ddd;
}
.s-up-k input{
    height:100%;
}
.s-up-loading{
    position: absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    background-color: rgba(0,0,0,0.5);
}
.s-load-tb{
    display: inline-block;
    width: 30px;
    height: 30px;
    background-image: url(../img/loading.gif);
    background-size: contain;
    background-position: center;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -15px;
    margin-top: -15px;
    z-index: 4;

}
.s-up-k2{
    position: relative;
    padding: 0;
    width: 80px;
    height: 80px;
    overflow:hidden;
    background-color: #fff;
    border: 1px solid #ddd;
}
.s-up-k2 input{
    height:100%;
}
.s-up-img{
    display:flex;
    align-items: center;
    width: 80px;
    height: 80px;
    overflow: hidden;
}
.s-up-close{
    position: absolute;
    display: none;
    right:-10px;
    top:-10px;
    width: 20px;
    height: 20px;
    background-image: url("../img/new_06.png");
    background-size: contain;
    background-position: center;
}
.s-up-add{
    position: relative;
    text-align: center;
}
.s-add-img{
    position: absolute;
    width: 26px;
    height: 25px;
    top: 50%;
    margin-left: -13px;
    margin-top: -13px;
    left: 50%;
    display: inline-block;
    background-image: url("../img/new_03.png");
}
.s-up-wcon{
    position: relative;
    float: left;
    margin-right: 15px;
    display: inline-block;
    margin-bottom: 10px;
}
.gg-attr-img{
    margin-top: 5px;
}
.s-cut-pic{
	display:none;
    width: 100%;
    line-height: 30px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background-color: #e78b24;
    cursor: pointer;
}

/*裁剪圖片樣式*/
.imgAreaDiv{
    display: none;
}
.img-area-mask{
    position: fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color: #ccc;
    opacity:0.5;
    z-index: 98;
}
.img-area-k{
    position: fixed;
    width: 600px;
    height: 410px;
    top:50%;
    margin-top: -220px;
    left: 50%;
    margin-left: -300px;
    border: 1px solid #ddd;
    background-color: #fff;
    z-index: 99;
}
.imgAreaDiv img{
	max-width: none;
}
    
.img-area-title{
    position: relative;
    border-bottom: 1px solid #ddd;
    line-height: 35px;
    color: #fff;
    background-color: #e78b24;
    padding-left: 10px;
    font-size: 14px;
}
.img-area-close{
    position: absolute;
    display: none;
    right: 0;
    top:0;
    cursor:pointer;
    width: 20px;
    height: 20px;
    display: inline-block;
}
.img-area-con{
    display: flex;
    height: 325px;
}
.img-area-ys{
	padding-top: 10px;
    width: 350px;
    height: 325px;
    text-align: center;
    overflow: auto;
    border-right:1px solid #ddd;
}
.img-area-ys img{
}
.img-area-cj{
    width: 250px;
}
.img-cj-txt{
    width: 100%;
    line-height: 30px;
    font-size: 14px;
    text-align: center;
    border-bottom: 1px solid #ddd;
}
.img-cj-con{
    width: 100%;
    text-align: center;
}
.img-before-photo{
	width:300px;
}
.img-cj-pic{
    margin: 20px auto 0 auto;
    width: 150px;
    height:150px;
    overflow: hidden;
}
.img-cj-pic img{
	 width: 150px;
    height:150px;
}
.img-area-pic{
    padding: 5px 10px;
    font-size: 14px;
    float: right;
    margin-top: 2px;
    margin-right: 10px;
    border: 1px solid #ddd;
    background-color: #e78b24;
    color: #fff;
}
.img-area-footer{
    height: 30px;
    border-top:1px solid #ddd;
}

外掛下載地址:http://download.csdn.net/download/jylonger/10141917