h5 端图片上传

1、upload.js

(function($) {
    $.extend($.fn, {
        images : new Array(),
        initImages:function (images) {
            $.each(images,function (index,value) {
                $(this).images.push(value);
                var $img = $('<div><div class="try-report-add thumb"><img class="dataImg" src='+ConstUtil.get("PIC_DOMAIN")+value+'></div>' +
                    '<img onclick="$(this).delImage(\''+value+'\',this)"  src="/pages/prod/activity/try/images/try-delete.png"></div>');
                $("#upImg").append($img);
            })
        },
        getImages: function () {
            return $(this).images;
        },
        delImage: function (url,e) {
            for(i in $(this).images){
                if(url == $(this).images[i]){
                    $(this).images.splice(i,1);
                }
            }
            $(e).parent().remove();
            $("#upload").show();
        },
        fileUpload: function(opts) {
            this.each(function() {
                var $self = $(this);
                var quality = opts.quality ? opts.quality / 50 : 0.5;
                var dom = {
                    "fileToUpload": $self.find(".fileToUpload"),
                    "thumb": $self.find(".thumb"),
                    "progress": $self.find(".upload-progress")
                };
                var funs = {
                    bindEvent: function() {
                        console.log(dom.fileToUpload)
                        // $self.click(function(){
                        //     dom.fileToUpload.click(function (event) {
                        //         event.stopPropagation();//防止事件冒泡
                        //     }).click();
                        // });
                        dom.fileToUpload.on("change", function() {
                            if($(this).images.length>=opts.maxNum){
                                alert("最多只能上传"+opts.maxNum+"图片");
                                return;
                            }
                            funs.fileSelect(this);
                        });
                    },
                    fileSelect: function(obj) {
                        for(var i=0;i<obj.files.length;i++) {
                            var file = obj.files[i];
                            var reader = new FileReader();
                            reader.onload = function () {
                                var image = new Image();
                                image.src = reader.result;
                                image.onload = function () {
                                    var wdh = Number(image.width)>Number(image.heihgt)? true : false;
                                    var data = funs.compress(this);
                                    funs.fileUpload(data, file.type,wdh);
                                };
                            };
                            reader.readAsDataURL(file);
                        }
                    },
                    fileUpload: function(data,type,wdh) {
                        if(type.indexOf('jpeg')>-1) type='image/jpg';
                        var text = window.atob(data.split(',')[1]);
                        var ia = new Uint8Array(text.length);
                        for (var i = 0; i < data.length; i++) {
                            ia[i] = text.charCodeAt(i);
                        };

                        var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder;
                        var blob;

                        if (Builder) {
                            var builder = new Builder();
                            builder.append(ia);
                            blob = builder.getBlob(type);
                        } else {
                            blob = new window.Blob([ia], {type: type});
                        }
                        var fd = new FormData();
                        fd.append(opts.file, blob);
                        var xhr = new XMLHttpRequest();
                        xhr.addEventListener("load", opts.success, false);
                        xhr.addEventListener("error", opts.error, false);
                        xhr.open("POST", opts.url);
                        xhr.send(fd);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                var ret = JSON.parse(xhr.responseText);
                                console.log(ret);
                                console.log(ret.state);
                                if(ret.state=='SUCCESS'){
                                    var commentListLiHeight = Number((window.screen.width)*0.92*0.3).toFixed(1);
                                    if(wdh){
                                        var $img = $('<li class="li-img"><a style="height: '+commentListLiHeight+'px;" href="javascript:;"><img class="dataImg" onclick="CommentDetail.initSwiper(this)" style="width: 100%;" src='+ret.url+'></a>' +
                                            '<i class="icon-del" onclick="$(this).delImage(\''+ret.savepath+'\',this)"></i></li>');
                                    }else{
                                        var $img = $('<li class="li-img"><a style="height: '+commentListLiHeight+'px;" href="javascript:;"><img class="dataImg" onclick="CommentDetail.initSwiper(this)" style="height: 100%;" src='+ret.url+'></a>' +
                                            '<i class="icon-del" onclick="$(this).delImage(\''+ret.savepath+'\',this)"></i></li>');
                                    }
                                    $("#upImg").prepend($img);
                                    $(this).images.push(ret.savepath);
                                    if($(this).images.length==opts.maxNum){
                                        $("#upload").hide();
                                    }
                                }
                            }
                        };
                    },
                    compress: function(img) {
                        var canvas = document.createElement("canvas"),
                            ctx = canvas.getContext('2d'),
                            tCanvas = document.createElement("canvas"),//瓦片canvas
                            tctx = tCanvas.getContext("2d");
                        var initSize = img.src.length;
                        var width = img.width;
                        var height = img.height;

                        //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
                        var ratio;
                        if ((ratio = width * height / 4000000)>1) {
                            ratio = Math.sqrt(ratio);
                            width /= ratio;
                            height /= ratio;
                        }else {
                            ratio = 1;
                        }

                        canvas.width = width;
                        canvas.height = height;

//        铺底色
                        ctx.fillStyle = "#fff";
                        ctx.fillRect(0, 0, canvas.width, canvas.height);

                        //如果图片像素大于100万则使用瓦片绘制
                        var count;
                        if ((count = width * height / 1000000) > 1) {
                            count = ~~(Math.sqrt(count)+1); //计算要分成多少块瓦片

//            计算每块瓦片的宽和高
                            var nw = ~~(width / count);
                            var nh = ~~(height / count);

                            tCanvas.width = nw;
                            tCanvas.height = nh;

                            for (var i = 0; i < count; i++) {
                                for (var j = 0; j < count; j++) {
                                    tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);

                                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                                }
                            }
                        } else {
                            ctx.drawImage(img, 0, 0, width, height);
                        }

                        //进行最小压缩
                        console.log('*****',quality)
                        var ndata = canvas.toDataURL('image/jpeg', quality);

                        console.log('压缩前:' + initSize);
                        console.log('压缩后:' + ndata.length);
                        console.log('压缩率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");

                        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;

                        return ndata;
                    }
                };
                funs.bindEvent();
            });
        }
    });
})($);

2、调用

var CommentDetail = {
    bindEvent : function () {
        var url ="/js/ueditor/jsp/uploader.jsp?action=uploaduser&dirName=comment&needCompress=true";  //上传路径
        $("#upload").fileUpload({
            "url": url,
            "file": "comment",
            "maxNum": 6
        });
    }

3、html

<div class="try-my-push clearfix">
                <ul class="list" id="upImg">
                    <!--<iframe id="upframe" name="upframe" src="" style="display:none;"> </iframe>-->
                    <li class="try-report-btn" id="upload">
                        <a href="javascript:;">
                            <img src="images/input-file-default.png" alt="" width="100%;"style="max-width: 100%;">

                        <!--<form action="/plugins/ueditor/jsp/uploader.jsp?action=uploaduser&dirName=headimg&needCompress=true"-->
                        <!--method="POST" id="form1" enctype="multipart/form-data">-->
                            <input type="file" id="front-file" class="fileToUpload img-file">
                        </a>
                        <!--</form>-->
                    </li>
                </ul>
            </div>

可以实现单张图片压缩后上传,无法多张上传,通过for循环 多次异步请求,结果有可能返回同一个结果或者返回多个结果,但是是同一个图片。

posted @ 2017-11-15 15:53  我爱小明  阅读(770)  评论(0编辑  收藏  举报