An image upload plugin, including generating preview images after image upload

Publish an image upload plugin, generate preview images after uploading images

Effect within the project

Plugin code:

/**
 * zx-upload.js v1.0.0
 * 上传插件
 * http://www.*.com/
 *
 * Copyright 2018-2028 zxhj963
 *
 * Released on: 2018/7/21
 */
 ; (function ($, window, document, undefined) {
    "use strict";
    var defaults = {
        isLayer:true,
        maxCount: 5,
        curCount: 0,
        urls: '',
        limitWidth: 500,
        limitHeight: 500,
        viewWidth: 80,
        viewHeight: 80,
        errViewImg:'../images/noimage.gif',
        savePath: '/upload/upload/upload/',
        saveServerUrl: "uploadBase64Img.asp"
    };

    function Upload($ele, options) {
        this.$ele = $ele;
        this.options = $.extend({}, defaults, options);
        console.log(this.options)
        this.init();
    }
    Upload.prototype = {
        constructor: Upload,
        init: function () {
            this.renderViewBox();
            this.bindAddEven();
            this.bindEditEven();
            this.bindDelEven();
        },
        clearViewItem: function () {
            this.$ele.find('.view-item').remove();  //清除所有的view-item
        },
        showUploadBtn: function () {
            this.$ele.children('.zx-view-box').children('label.button').show(); //显示上传按钮
        },
        hideUploadBtn: function () {
            this.$ele.children('.zx-view-box').children('label.button').hide(); //隐藏上传按钮
        },
        resizeImgSize: function (originWidth, originHeight, maxWidth, maxHeight) {
            var targetWidth = originWidth, targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                    // 更宽,按照宽度限定尺寸
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
            }
            else {
                targetWidth = originWidth;
                targetHeight = originHeight;
            }
            return {
                w: targetWidth,
                h: targetHeight
            }
        },
        getImageSize: function (url,callback) {
            var img = new Image();
            img.src = url;
            // 如果图片被缓存,则直接返回缓存数据
            if (img.complete) {
                var ret =  {
                    w: img.width,
                    h: img.height
                };
                callback(ret)
            } else {
                // 完全加载完毕的事件
                img.onload = function () {
                    var ret = {
                        w: img.width,
                        h: img.height
                    };
                    callback(ret)
                }
            }
            return ret;
        },
        getImgUrlBase64: function (imageObj, targetSize) {
            var canvas = document.createElement('canvas');
            //创建预览图片
            canvas.width = targetSize.w;
            canvas.height = targetSize.h;
            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);         // 清除画布
            ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
            var Img64 = canvas.toDataURL();   // 压缩后的base64串
            return Img64;
        },
        getInputUrls: function () {
            //获取文本框中的链接和链接数量
            var that = this,
                urls = that.$ele.children('input.zx-urlInput').val(),
                urls_arr = urls.split(','),
                counts = (urls == '') ? 0 : urls_arr.length,
                maxCount = this.options.maxCount;
            if (counts >= maxCount) {
                var temp_arr = [];
                urls_arr.forEach(function (e, i) {
                    if (i < maxCount) { temp_arr.push(e); }
                });
                urls = temp_arr.join(',');
                counts = maxCount;
                that.hideUploadBtn();
            }
            else {
                that.showUploadBtn();
            }
            that.$ele.children('input.zx-urlInput').val(urls);
            return {
                urls: urls,
                counts: counts
            };
        },
        renderViewBox: function () {
            var that = this;
            that.clearViewItem(); 
            var curUrls = that.getInputUrls().urls;
            var curCount = that.getInputUrls().counts;
            if (curCount > 0) {
                var arr_Urls = curUrls.split(',');
                arr_Urls.forEach(function (e, i) {
                    if (i < that.options.maxCount) {
                        var viewImg64 = that.options.errViewImg;
                        var viewItemHtml = '<div class="view-item"><img src="' + viewImg64 + '" /><div class="admin-box"><a href="javascript:void(0);"  class="edit-btn" data-inputName="pic_1">编辑</a> | <a href= "javascript:void(0);"  class="del-btn" >删除</a></div></div>';
                        that.$ele.children('.zx-view-box').append(viewItemHtml);
                        //e为文本框中的图片链接地址,需转换成viewImg64的预览图片地址
                        that.getImageSize(e, function (ret) {
                            var viewImg64Size = that.resizeImgSize(ret.w, ret.h, that.options.viewWidth, that.options.viewHeight);
                            var imgView = new Image();
                            imgView.src = e;
                            imgView.onload = function () {
                                var viewImg64 = '';
                                if (imgView.fileSize > 0 || (imgView.width > 0 && imgView.height > 0)) {
                                    viewImg64 = that.getImgUrlBase64(imgView, viewImg64Size)
                                } else {
                                    viewImg64 = that.options.errViewImg;
                                }
                                that.$ele.children('.zx-view-box').find('.view-item').eq(i).children('img').attr('src', viewImg64);
                            }
                        });
                    } else {
                    }
                });
            }
        },
        bindAddEven: function () {
            var that = this; 
            var newUrls = '', msg='';
            that.$ele.children('.zx-view-box').on('change', '.zx-fileInput', function () {
                var curUrls = that.getInputUrls().urls;
                var curCount = that.getInputUrls().counts;
                newUrls = curUrls;
                if (curCount >= that.options.maxCount) {
                    return false;
                }
                else {
                    var file = this.files[0];
                    var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
                    if (!rFilter.test(file.type)) {
                        if (that.options.isLayer) {
                            msg = '数据错误,提交的数据不是文件!';
                            if (that.options.isLayer) {
                                layer.alert(msg, { icon: 2 });
                            } else {
                                alert(msg);
                            }
                        } else {
                            msg = '文件格式不正确!';
                            if (that.options.isLayer) {
                                layer.alert(msg, { icon: 2 });
                            } else {
                                alert(msg);
                            }
                        }
                        return false;
                    }
                    else {
                        if (!!file) {
                            //是图片文件,开始上传到服务器
                            var reader = new FileReader();
                            reader.readAsDataURL(file);  // 图片文件转换为base64
                            reader.onload = function () {   // 文件加载完成
                                var def_url = this.result;  //图片原图的base64链接  
                                var image = new Image();
                                image.src = def_url;
                                image.onload = function () {
                                    var originWidth = this.width, originHeight = this.height;   // 图片原始尺寸
                                    var limitWidth = that.options.limitWidth, limitHeight = that.options.limitHeight;    // 保存图片的最大尺寸限制
                                    var targetSize = that.resizeImgSize(originWidth, originHeight, limitWidth, limitHeight);   // 图片尺寸超过限制,调整尺寸
                                    var targetImg64 = that.getImgUrlBase64(image, targetSize);
                                    var formData = new FormData();
                                    formData.append("imgUrl", targetImg64);
                                    formData.append("savePath", that.options.savePath);
                                    $.ajax({
                                        type: "POST",
                                        url: that.options.saveServerUrl, 
                                        data: formData,
                                        dataType: "json", //声明成功使用json数据类型回调
                                        //如果传递的是FormData数据类型,那么下来的三个参数是必须的,否则会报错
                                        cache: false,  //默认是true,但是一般不做缓存
                                        processData: false, //用于对data参数进行序列化处理,这里必须false;如果是true,就会将FormData转换为String类型
                                        contentType: false,  //一些文件上传http协议的关系,自行百度,如果上传的有文件,那么只能设置为false
                                        success: function (ret) {  //请求成功后的回调函数
                                            if (ret.code == 200) {
                                                msg = '<span class="icon-check"> 上传成功!</div>';
                                                if (that.options.isLayer) {
                                                    layer.msg(msg, {area:['','46px'], title: false });
                                                } else {
                                                    alert(msg);
                                                }
                                                var imgUrl = ret.msg;
                                                //将上传成功后返回得到的链接添加到当前urls的后面
                                                newUrls = (curUrls == "") ? imgUrl : (newUrls + "," + imgUrl);
                                                that.$ele.children('input.zx-urlInput').val(newUrls);  //更新文本框的值

                                                //生成缩略图
                                                var imageView = new Image();
                                                imageView.src = imgUrl;
                                                imageView.onload = function () {
                                                    var viewSize = that.resizeImgSize(originWidth, originHeight, that.options.viewWidth, that.options.viewHeight);
                                                    var viewImg64 = that.getImgUrlBase64(imageView, viewSize);
                                                    var viewItemHtml = '<div class="view-item"><img src="' + viewImg64 + '" /><div class="admin-box"><a href="javascript:void(0);"  class="edit-btn" data-inputName="pic_1">编辑</a> | <a href= "javascript:void(0);"  class="del-btn" >删除</a></div></div>';
                                                    that.$ele.children('.zx-view-box').append(viewItemHtml);
                                                    if (that.getInputUrls().counts >= that.options.maxCount) {
                                                        that.hideUploadBtn();
                                                    }
                                                    else {
                                                        return false;
                                                    }
                                                };                                                
                                            }
                                            else {
                                                msg = '上传失败!';
                                                if (that.options.isLayer) {
                                                    layer.alert(msg, { icon: 2 });
                                                } else {
                                                    alert(msg);
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            return false;
                        }
                    }




                }
            });
        },
        bindEditEven: function () {
            var that = this;
            that.$ele.children('.zx-view-box').on('click', '.edit-btn', function () {
                var msg = '编辑功能开发中。。。!';
                if (that.options.isLayer) {
                    layer.alert(msg, { icon: 2 });
                } else {
                    alert(msg);
                }
            });
        },
        bindDelEven: function () {
            var that = this;
            var newUrls = '';
            that.$ele.children('.zx-view-box').on('click', '.del-btn', function () {
                //删除当前预览项
                var index = $(this).parents('.view-item').index();  //当前item的序号;用于删除input当中的值
                var curUrls = that.getInputUrls().urls;
                var curCount = that.getInputUrls().counts;
                if (curCount > 0) {
                    var urls_arr = curUrls.split(',');
                    var temp_arr = [];
                    urls_arr.forEach(function (e, i) {
                        if (i != index - 1) { temp_arr.push(e); }
                        else { }
                    });
                    newUrls = temp_arr.join(','); 
                    $(this).parents('.view-item').remove();
                } else {
                    newUrls = '';
                }
                that.showUploadBtn();
                that.$ele.children('input.zx-urlInput').val(newUrls);
            });
        }
    };

    $.fn.ZX_upload = function (options) {
        options = $.extend(defaults, options || {});    //合并对象
        return new Upload($(this), options);
    }
})(jQuery, window, document);

Paste the code first!
How to use the plugin:

This plugin needs to rely on the jquery library. I use jquery-1.12.4.js. In addition, the layer plugin can be referenced according to your needs or not, but if isLayer in the options parameter is set to true, you must Introduce the layer library

Jquery.js first reference library, I use jquery-1.12.4.js,
reintroduction layer.js library
reintroduction pintuer UI, does not refer to the need to adjust according to the actual needs of style;

Call the plug-in method in the project:

    <script type="text/javascript" src="../js/jquery.zx-upload.js"></script>
    <script type="text/javascript">
        $(function () {
            var upload1 = $('.upload-box-1').ZX_upload({
                maxCount: 1
            });
            var upload2 = $('.upload-box-2').ZX_upload({
                maxCount: 5
            });

        });

    </script>

Disadvantages: You cannot upload multiple pictures, you can only upload one picture at a time.

**特别注意**
1. 上传图片的接口,是以二进制流的格式传递的,所以在获取数据时要注意。(ASP后台建议使用各类无组件文件上传类,如:AnUpLoad上传类等,有需要的可以给我留言)
2. 文件上传接口需要提供的数据格式为json格式,上传成功需要得到{code:200,msg:""},msg中为上传后的图片链接,如果上传失败,则需要将code给成其他值既可以。

Mark: 2018/7/21 18:05 The editing function is still under development due to time.

Published 10 original articles · won 11 · 30,000+ views

Guess you like

Origin blog.csdn.net/zxhj963/article/details/81147544