利用lrz.bundle.js实现图片压缩上传

  作者:winnie

html部分:<form action="" method="post" enctype="multipart/form-data"> <input class="upl

html部分:

<form action="" method="post" enctype="multipart/form-data">

<input class="upload-name-img-input" type="file"  name="file" accept="image/*" value="">

</form>


js部分:

下载

<script src="./js/compress/lrz.bundle.js"></script>  

下载地址: https://github.com/think2011/localResizeIMG

<script src="./js/jquery.min.js"></script>


//图片上传压缩方法

function compressImg(fileDom,form,callback){

    var that = fileDom;

    lrz(that.files[0], {

        width: 800   //width:640这个代表的是图片占得内存的大小,值越小,占内存越小

    }).then(function (rst) {

        // 表单另外所带的参数

        form.serializeArray().map(function (x) {

        rst.formData.append(x.name,x.value);

    });

        callback(rst.formData);

    });

}

// 上传按钮注册事件

$('.upload-name-img-input').live('change',function(event){

    if (isUploadImgFlag) {

        isUploadImgFlag = false;

        setImgUploadDisable();

        var currDom = $(this);

        var files = event.target.files;

        var fileSize = files[0].size;

        if (parseInt(fileSize) > 30 * 1024 * 1024) {

            currDom.val('');

            isUploadImgFlag = true;

            return false;

        }

        compressImg(this,currDom.parents('form'),function(formData){

            $.ajax({

                url: "uploadUrl", // 上传文件接口地址

                data: formData,

                cache: false,

                // async:false,

                processData: false,

                contentType: false,

                type: 'post',

                dataType:'json',

                success: function (data) {

                    // data=JSON.parse(data);

                    currDom.parents('.upload-name-img-btn').prev().find('.uploading-li').hide();

                if(data.success){

                    consolel.log("上传成功")

                }else{

                    console.log(data.msg);

                }

                    isUploadImgFlag = true;

                },

                error: function(){

                    isUploadImgFlag = true;

                }

            });

        });

    }

});


猜你喜欢