zoukankan      html  css  js  c++  java
  • 对百度WebUploader的二次封装,精简前端代码之图片预览上传(两句代码搞定上传)

    前言

    本篇文章上一篇:

    对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)

    此篇是在上面的基础上扩展出来专门上传图片的控件封装.

    首先我们看看效果:

    正文

    使用方式同样很简单,首先创建HTML容器如下:

    <div id="uploader" class="uploaderPic"> </div>

    然后页面加载完成后渲染:

        $(function () {
            $("#uploader").powerWebUpload({ auto: false });
        })

    就搞定了.

    下面还是老规矩,直接上源码:

    /*
    基于百度webuploader的图片上传JQ插件(需引用JQ)
    作者:顾振印
    时间:2016-07-07
    */
    
    (function ($, window) {
        var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../..";
        var UpdataLoadarrayObj = new Array();
        function SuiJiNum() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
    
        function initWebUpload(item, options) {
    
            if (!WebUploader.Uploader.support()) {
                var error = "上传控件不支持您的浏览器!请尝试升级flash版本或者使用Chrome引擎的浏览器。<a target='_blank' href='http://se.360.cn'>下载页面</a>";
                if (window.console) {
                    window.console.log(error);
                }
                $(item).text(error);
                return;
            }
            var target = $(item);//容器
            if (target.find(".uploader-list").length > 0) {
                return;
            }
            //创建默认参数
            var defaults = {
                auto: true,
                hiddenInputId: "uploadifyHiddenInputId", // input hidden id
                onAllComplete: function (event) { }, // 当所有file都上传后执行的回调函数
                onComplete: function (event) { },// 每上传一个file的回调函数
                fileNumLimit: undefined,//验证文件总数量, 超出则不允许加入队列
                fileSizeLimit: undefined,//验证文件总大小是否超出限制, 超出则不允许加入队列。
                fileSingleSizeLimit: undefined,//验证单个文件大小是否超出限制, 超出则不允许加入队列
                PostbackHold: false
            };
            var opts = $.extend(defaults, options);
            var hdFileData = $("#" + opts.hiddenInputId);
            var pickerid = "";
            if (typeof guidGenerator36 != 'undefined')//给一个唯一ID
                pickerid = guidGenerator36();
            else
                pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            var uploaderStrdiv = '<div class="webuploader">'
            if (opts.auto) {
                uploaderStrdiv =
                '<div  class="uploader-list"></div>' +
                '<div class="btns">' +
                '<div id="' + pickerid + '">选择文件</div>' +
                '</div>'
    
            } else {
                uploaderStrdiv =
                '<div  class="uploader-list"></div>' +
                '<div class="btns">' +
                '<div id="' + pickerid + '">选择文件</div>' +
                '<button class="webuploadbtn">开始上传</button>' +
                '</div>'
            }
            uploaderStrdiv += '<div style="display:none" class="UploadhiddenInput" >
                             </div>'
            uploaderStrdiv += '</div>';
            target.append(uploaderStrdiv);
    
            var $list = target.find('.uploader-list'),
                 $btn = target.find('.webuploadbtn'),//手动上传按钮备用
                 state = 'pending',
                 $hiddenInput = target.find('.UploadhiddenInput')
            var jsonData = {
                fileList: []
            };
            debugger;
            var webuploaderoptions = $.extend({
    
                // swf文件路径
                swf: applicationPath + '/Scripts/webuploader/Uploader.swf',
                // 文件接收服务端。
                server: '/Home/AddFile',
                deleteServer: '/Home/DeleteFile',
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建,可能是input元素,也可能是flash.
                pick: '#' + pickerid,
                //不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
                resize: false,
                runtimeOrder: 'flash',
                fileNumLimit: opts.fileNumLimit,
                fileSizeLimit: opts.fileSizeLimit,
                fileSingleSizeLimit: opts.fileSingleSizeLimit,
                //限制只能上传图片,格式gif,jpg,jpeg,bmp,png
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/*'
                }
            },
            opts);
            var uploader = WebUploader.create(webuploaderoptions);
            UpdataLoadarrayObj[$(item)[0].id] = uploader;
           var  ratio = window.devicePixelRatio || 1
    
            // 缩略图大小
           var thumbnailWidth = 110 * ratio
           var thumbnailHeight = 110 * ratio
           if (opts.auto) {
               // 优化retina, 在retina下这个值是2
    
               uploader.on('fileQueued', function (file) {
    
                   var $li = $('<div id="' + $(item)[0].id + file.id + '" class="file-item thumbnail">' +
                               '<img>' +
                               '<div class="info">' + file.name + '</div>' +
                              '</div>');
    
                   $img = $li.find('img');
                   uploader.makeThumb(file, function (error, src) {
                       if (error) {
                           $img.replaceWith('<span>不能预览</span>');
                           return;
                       }
    
                       $img.attr('src', src);
                   }, thumbnailWidth, thumbnailHeight);
    
                   // $list为容器jQuery实例
                   $list.append($li);
    
                   $btns = $('<div class="file-panel">' +
                  '<span class="cancel">删除</span>').appendTo($li)
                   uploader.upload();
               });
           } else {
               uploader.on('fileQueued', function (file) {//队列事件
    
                   var $li = $('<div id="' + $(item)[0].id + file.id + '" class="file-item thumbnail">' +
                               '<img>' +
                               '<div class="info">' + file.name + '</div>' +
                              '</div>');
    
                   $img = $li.find('img');
                   uploader.makeThumb(file, function (error, src) {
                       if (error) {
                           $img.replaceWith('<span>不能预览</span>');
                           return;
                       }
    
                       $img.attr('src', src);
                   }, thumbnailWidth, thumbnailHeight);
    
                   // $list为容器jQuery实例
                   $list.append($li);
    
                   $btns = $('<div class="file-panel">' +
                  '<span class="cancel">删除</span>').appendTo($li)
               });
           }
            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', function (file, percentage) {
                var $li = $('#' + $(item)[0].id + file.id),
                    $percent = $li.find('.progress span');
    
                // 避免重复创建
                if (!$percent.length) {
                    $percent = $('<p class="progress"><span></span></p>')
                            .appendTo($li)
                            .find('span');
                }
    
                $percent.css('width', percentage * 100 + '%');
            });
    
            // 文件上传成功,给item添加成功class, 用样式标记上传成功。
            uploader.on('uploadSuccess', function (file, response) {
                $('#' + $(item)[0].id + file.id).addClass('upload-state-done');
                var $li = $('#' + $(item)[0].id + file.id),
                    $error = $li.find('div.error');
    
                // 避免重复创建
                if (!$error.length) {
                    $error = $('<div class="success"></div>').appendTo($li);
                }
                if (response.state == "error") {
                    $error.text(response.message);
                } else {
                    $error.text('上传完成');
                    $hiddenInput.append('<input type="text" id="hiddenInput' + $(item)[0].id + file.id + '" class="hiddenInput" value="' + response.message + '" />')
                }
              
            });
    
            // 文件上传失败,显示上传出错。
            uploader.on('uploadError', function (file) {
                var $li = $('#' + $(item)[0].id + file.id),
                    $error = $li.find('div.error');
    
                // 避免重复创建
                if (!$error.length) {
                    $error = $('<div class="error"></div>').appendTo($li);
                }
    
                $error.text('上传失败');
            });
    
            // 完成上传完了,成功或者失败,先删除进度条。
            uploader.on('uploadComplete', function (file, response) {
                $('#' + $(item)[0].id + file.id).find('.progress').remove();
            });
    
            //uploader.on('uploadProgress', function (file, percentage) {//进度条事件
            //    var $li = target.find('#' + $(item)[0].id + file.id),
            //        $percent = $li.find('.progress .bar');
    
            //    // 避免重复创建
            //    if (!$percent.length) {
            //        $percent = $('<span class="progress">' +
            //            '<span  class="percentage"><span class="text"></span>' +
            //          '<span class="bar" role="progressbar" style=" 0%">' +
            //          '</span></span>' +
            //        '</span>').appendTo($li).find('.bar');
            //    }
    
            //    $li.find('span.webuploadstate').html('上传中');
            //    $li.find(".text").text(Math.round(percentage * 100) + '%');
            //    $percent.css('width', percentage * 100 + '%');
            //});
            //uploader.on('uploadSuccess', function (file, response) {//上传成功事件
            //    if (response.state == "error") {
            //        target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html(response.message);
            //    } else {
            //        target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html('已上传');
            //        $hiddenInput.append('<input type="text" id="hiddenInput' + $(item)[0].id + file.id + '" class="hiddenInput" value="' + response.message + '" />')
            //    }
            //});
    
            //uploader.on('uploadError', function (file) {
            //    target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html('上传出错');
            //});
    
            //uploader.on('uploadComplete', function (file) {//全部完成事件
            //    target.find('#' + $(item)[0].id + file.id).find('.progress').fadeOut();
            //});
    
    
    
            uploader.on('all', function (type) {
                if (type === 'startUpload') {
                    state = 'uploading';
                } else if (type === 'stopUpload') {
                    state = 'paused';
                } else if (type === 'uploadFinished') {
                    state = 'done';
                }
    
                if (state === 'uploading') {
                    $btn.text('暂停上传');
                } else {
                    $btn.text('开始上传');
                }
            });
    
            //删除时执行的方法
            uploader.on('fileDequeued', function (file) {
                debugger;
                var fullName = $("#hiddenInput" + $(item)[0].id + file.id).val();
                if (fullName != null) {
                    $.post(webuploaderoptions.deleteServer, { fullName: fullName }, function (data) {
                        // alert(data.message);
                    })
                }
                $("#" + $(item)[0].id + file.id).remove();
                $("#hiddenInput" + $(item)[0].id + file.id).remove();
    
            })
    
            //多文件点击上传的方法
            $btn.on('click', function () {
                if (state === 'uploading') {
                    uploader.stop();
                } else {
                    uploader.upload();
                }
            });
    
            //删除
            $list.on("click", ".file-panel", function () {
                debugger
                var $ele = $(this);
                var id = $ele.parent().attr("id");
                var id = id.replace($(item)[0].id, "");
    
                var file = uploader.getFile(id);
                uploader.removeFile(file);
            });
    
        }
        $.fn.CleanUpload = function (options) {
            var uploadrFile = UpdataLoadarrayObj[$(this).attr("id")]
            var fileslist = uploadrFile.getFiles();
            for (var i in fileslist) {
                uploadrFile.removeFile(fileslist[i]);
            }
            //var ele = $(this);
            //var filesdata = ele.find(".UploadhiddenInput");
            //filesdata.find(".hiddenInput").remove();
            //ele.find(".uploader-list .item").remove();
        }
        $.fn.GetFilesAddress = function (options) {
            var ele = $(this);
            var filesdata = ele.find(".UploadhiddenInput");
            var filesAddress = [];
            filesdata.find(".hiddenInput").each(function () {
                filesAddress.push($(this).val());
            })
            return filesAddress;
    
        }
    
        $.fn.powerWebUpload = function (options) {
            var ele = this;
    
            if (typeof WebUploader == 'undefined') {
                var casspath = applicationPath + "/Scripts/webuploader/webuploader.css";
                $("<link>").attr({ rel: "stylesheet", type: "text/css", href: casspath }).appendTo("head");
                var jspath = applicationPath + "/Scripts/webuploader/webuploader.min.js";
                $.getScript(jspath).done(function () {
    
                    initWebUpload(ele, options);
                })
                .fail(function () {
                    alert("请检查webuploader的路径是否正确!")
                });
    
            }
            else {
                initWebUpload(ele, options);
            }
        }
    })(jQuery, window);

    因为有一些样式上的东西,所以还需要添加一部分CSS如下:

        #container {
            color: #838383;
            font-size: 12px;
        }
    
        .uploaderPic .queueList {
            margin: 20px;
            border: 3px dashed #e6e6e6;
        }
    
            .uploaderPic .queueList.filled {
                padding: 17px;
                margin: 0;
                border: 3px dashed transparent;
            }
    
            .uploaderPic .queueList.webuploader-dnd-over {
                border: 3px dashed #999999;
            }
    
        .uploaderPic p {
            margin: 0;
        }
    
        .element-invisible {
            position: absolute !important;
            clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
            clip: rect(1px,1px,1px,1px);
        }
    
        .uploaderPic .placeholder {
            min-height: 350px;
            padding-top: 178px;
            text-align: center;
            background: url(../images/image.png) center 93px no-repeat;
            color: #cccccc;
            font-size: 18px;
            position: relative;
        }
    
            .uploaderPic .placeholder .webuploader-pick {
                font-size: 18px;
                background: #00b7ee;
                border-radius: 3px;
                line-height: 44px;
                padding: 0 30px;
                *width: 120px;
                color: #fff;
                display: inline-block;
                margin: 0 auto 20px auto;
                cursor: pointer;
                box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
            }
    
            .uploaderPic .placeholder .webuploader-pick-hover {
                background: #00a2d4;
            }
    
            .uploaderPic .placeholder .flashTip {
                color: #666666;
                font-size: 12px;
                position: absolute;
                width: 100%;
                text-align: center;
                bottom: 20px;
            }
    
                .uploaderPic .placeholder .flashTip a {
                    color: #0785d1;
                    text-decoration: none;
                }
    
                    .uploaderPic .placeholder .flashTip a:hover {
                        text-decoration: underline;
                    }
    
        .uploaderPic .filelist {
            list-style: none;
            margin: 0;
            padding: 0;
        }
    
            .uploaderPic .filelist:after {
                content: '';
                display: block;
                width: 0;
                height: 0;
                overflow: hidden;
                clear: both;
            }
    
            .uploaderPic .filelist li {
                width: 110px;
                height: 110px;
                background: url(../images/bg.png) no-repeat;
                text-align: center;
                margin: 0 8px 20px 0;
                position: relative;
                display: inline;
                float: left;
                overflow: hidden;
                font-size: 12px;
            }
    
                .uploaderPic .filelist li p.log {
                    position: relative;
                    top: -45px;
                }
    
                .uploaderPic .filelist li p.title {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    top: 5px;
                    text-indent: 5px;
                    text-align: left;
                }
    
                .uploaderPic .filelist li p.progress {
                    position: absolute;
                    width: 100%;
                    bottom: 0;
                    left: 0;
                    height: 8px;
                    overflow: hidden;
                    z-index: 50;
                    margin: 0;
                    border-radius: 0;
                    background: none;
                    -webkit-box-shadow: 0 0 0;
                }
    
                    .uploaderPic .filelist li p.progress span {
                        display: none;
                        overflow: hidden;
                        width: 0;
                        height: 100%;
                        background: #1483d8 url(../images/progress.png) repeat-x;
                        -webit-transition: width 200ms linear;
                        -moz-transition: width 200ms linear;
                        -o-transition: width 200ms linear;
                        -ms-transition: width 200ms linear;
                        transition: width 200ms linear;
                        -webkit-animation: progressmove 2s linear infinite;
                        -moz-animation: progressmove 2s linear infinite;
                        -o-animation: progressmove 2s linear infinite;
                        -ms-animation: progressmove 2s linear infinite;
                        animation: progressmove 2s linear infinite;
                        -webkit-transform: translateZ(0);
                    }
    
        @@-webkit-keyframes progressmove {
            0% {
                background-position: 0 0;
            }
    
            100% {
                background-position: 17px 0;
            }
        }
    
        @@-moz-keyframes progressmove {
            0% {
                background-position: 0 0;
            }
    
            100% {
                background-position: 17px 0;
            }
        }
    
        @@keyframes progressmove {
            0% {
                background-position: 0 0;
            }
    
            100% {
                background-position: 17px 0;
            }
        }
    
        .uploaderPic .filelist li p.imgWrap {
            position: relative;
            z-index: 2;
            line-height: 110px;
            vertical-align: middle;
            overflow: hidden;
            width: 110px;
            height: 110px;
            -webkit-transform-origin: 50% 50%;
            -moz-transform-origin: 50% 50%;
            -o-transform-origin: 50% 50%;
            -ms-transform-origin: 50% 50%;
            transform-origin: 50% 50%;
            -webit-transition: 200ms ease-out;
            -moz-transition: 200ms ease-out;
            -o-transition: 200ms ease-out;
            -ms-transition: 200ms ease-out;
            transition: 200ms ease-out;
        }
    
        .uploaderPic .filelist li img {
            width: 100%;
        }
    
        .uploaderPic .filelist li p.error {
            background: #f43838;
            color: #fff;
            position: absolute;
            bottom: 0;
            left: 0;
            height: 28px;
            line-height: 28px;
            width: 100%;
            z-index: 100;
        }
    
        .uploaderPic .filelist li .success {
            display: block;
            position: absolute;
            left: 0;
            bottom: 0;
            height: 40px;
            width: 100%;
            z-index: 200;
            background: url(../images/success.png) no-repeat right bottom;
        }
    
        .uploaderPic .filelist div.file-panel {
            position: absolute;
            height: 0;
            filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#80000000', endColorstr='#80000000');
            background: rgba( 0, 0, 0, 0.5 );
            width: 100%;
            top: 0;
            left: 0;
            overflow: hidden;
            z-index: 300;
        }
    
            .uploaderPic .filelist div.file-panel span {
                width: 24px;
                height: 24px;
                display: inline;
                float: right;
                text-indent: -9999px;
                overflow: hidden;
                background: url(../images/icons.png) no-repeat;
                margin: 5px 1px 1px;
                cursor: pointer;
            }
    
                .uploaderPic .filelist div.file-panel span.rotateLeft {
                    background-position: 0 -24px;
                }
    
                    .uploaderPic .filelist div.file-panel span.rotateLeft:hover {
                        background-position: 0 0;
                    }
    
                .uploaderPic .filelist div.file-panel span.rotateRight {
                    background-position: -24px -24px;
                }
    
                    .uploaderPic .filelist div.file-panel span.rotateRight:hover {
                        background-position: -24px 0;
                    }
    
                .uploaderPic .filelist div.file-panel span.cancel {
                    background-position: -48px -24px;
                }
    
                    .uploaderPic .filelist div.file-panel span.cancel:hover {
                        background-position: -48px 0;
                    }
    
        .uploaderPic .statusBar {
            height: 63px;
            border-top: 1px solid #dadada;
            padding: 0 20px;
            line-height: 63px;
            vertical-align: middle;
            position: relative;
        }
    
            .uploaderPic .statusBar .progress {
                border: 1px solid #1483d8;
                width: 198px;
                background: #fff;
                height: 18px;
                position: relative;
                display: inline-block;
                text-align: center;
                line-height: 20px;
                color: #6dbfff;
                position: relative;
                margin: 0 10px 0 0;
            }
    
                .uploaderPic .statusBar .progress span.percentage {
                    width: 0;
                    height: 100%;
                    left: 0;
                    top: 0;
                    background: #1483d8;
                    position: absolute;
                }
    
                .uploaderPic .statusBar .progress span.text {
                    position: relative;
                    z-index: 10;
                }
    
            .uploaderPic .statusBar .info {
                display: inline-block;
                font-size: 14px;
                color: #666666;
            }
    
            .uploaderPic .statusBar .btns {
                position: absolute;
                top: 10px;
                right: 20px;
                line-height: 40px;
            }
    
        #filePicker2 {
            display: inline-block;
            float: left;
        }
    
        .uploaderPic .statusBar .btns .webuploader-pick,
        .uploaderPic .statusBar .btns .uploadBtn,
        .uploaderPic .statusBar .btns .uploadBtn.state-uploading,
        .uploaderPic .statusBar .btns .uploadBtn.state-paused {
            background: #ffffff;
            border: 1px solid #cfcfcf;
            color: #565656;
            padding: 0 18px;
            display: inline-block;
            border-radius: 3px;
            margin-left: 10px;
            cursor: pointer;
            font-size: 14px;
            float: left;
        }
    
            .uploaderPic .statusBar .btns .webuploader-pick-hover,
            .uploaderPic .statusBar .btns .uploadBtn:hover,
            .uploaderPic .statusBar .btns .uploadBtn.state-uploading:hover,
            .uploaderPic .statusBar .btns .uploadBtn.state-paused:hover {
                background: #f0f0f0;
            }
    
        .uploaderPic .statusBar .btns .uploadBtn {
            background: #00b7ee;
            color: #fff;
            border-color: transparent;
        }
    
            .uploaderPic .statusBar .btns .uploadBtn:hover {
                background: #00a2d4;
            }
    
            .uploaderPic .statusBar .btns .uploadBtn.disabled {
                pointer-events: none;
                opacity: 0.6;
            }
  • 相关阅读:
    Vue路由配置
    vue项目 favicon.ico不显示解决方案
    Vux使用AjaxPlugin发送请求跨域问题解决
    改变vux样式,自定义样式
    Hive LLAP
    GitHub提交代码无contributions记录解决办法
    Java websocket+ nginx+redis负载均衡上实现单对单通讯
    springboot异步接口
    C#中$的用法(转载)
    vmware-tools灰色而无法安装的问题
  • 原文地址:https://www.cnblogs.com/GuZhenYin/p/6737460.html
Copyright © 2011-2022 走看看