WebUploader 案例【上传头像】

// html 
<div  style="margin-top:34px;" id="box_avatar">
                    <!--用来存放文件信息-->
                    <div style="float:left;height:115px;width:115px; margin-right:15px;">
                        <div class="imgWrap">
                            <img src="" id="avatar" style="width:110px;height:110px;" onerror="$(this).attr('src', '/Images/UserAvatar/lock.png')" />
                            <div class="progress"><span></span></div>
                            <div class="infobox"></div>
                        </div>
                    </div>
                    <div style="margin-left:15px;">
                        <div id="picker"></div>
                    </div>
  </div>

 

.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;
}


    .imgWrap .infobox {
        display: none;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        height: 18px;
        overflow: hidden;
        z-index: 50;
        margin: 0;
        background: rgba(0,0,0,0.1);
        color: green;
        font-weight: 500;
        text-align: center;
        line-height: 1.3;
    }

    .imgWrap .progress {
        display: none;
        position: absolute;
        width: 100%;
        bottom: 2px;
        left: 0;
        height: 5px;
        overflow: hidden;
        z-index: 50;
        margin: 0;
        border-radius: 2px;
        background: rgba(0,0,0,0.1);
        -webkit-box-shadow: 0 0 0;
    }

        .imgWrap .progress span {
            display: block;
            overflow: hidden;
            width: 0%;
            height: 100%;
            background: #1483d8;
            -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);
        }
css

 

$(function(){

        // 上传图片
        $("#box_avatar").Tx_UploadAvatar({
            uploader: new Object(),
            uploadtype: "avatar_teacherinfo"
        });

});

 

/* 
    作用 : 用户上传头像
*/
(function ($) {


    $.fn.Tx_UploadAvatar = function (option) {

        // 默认参数
        var _default = {
            uploader: new Object(),
            thumbnailWidth: 110,
            thumbnailHeight: 110,
            image: $("#avatar"),
            pick: { id: "#picker", label: "选择图片" },
            uploadtype: "",
            callback: function () { }
        }

        // 参数处理
        option = $.extend(_default, option);

        // Obj
        var _Obj = this;

        // 上传按钮

        var uploadBtn;

        // ratio
        var ratio = window.devicePixelRatio || 1;

        // 图片预览大小
        option.thumbnailWidth = option.thumbnailWidth * ratio;
        option.thumbnailHeight = option.thumbnailHeight * ratio;

        var createUploadBtn = function (text) {
            uploadBtn = $('<div class="webuploader-pick">' + text + '</div>').on("click", function () {
                $(this).remove();
                $(_Obj).find(".progress").show();
                option.uploader.upload();
            });
        };

        var changeProgress = function (width) {
            var $li = $(_Obj).find(".progress"),
               $percent = $li.find("span");
            $percent.css("width", width * 100 + "%");
        }

        option.uploader = WebUploader.create({
            pick: option.pick,
            // swf文件路径
            swf: '/Scripts/webuploader/Uploader.swf',

            // 文件接收服务端。
            server: '/UserCenter/UploadAvatar',
            // 内部根据当前运行是创建,可能是input元素,也可能是flash.
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            //文件数量
            fileNumLimit: 1,
            // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
            resize: false,
            //允许的图片大小
            fileSingleSizeLimit: 1 * 1024 * 1024,

            formData: {
                "uploadtype": option.uploadtype
            }
        });

        // 放入图片前,移除之前选择的图片,保证每次只有一张图片
        option.uploader.on("beforeFileQueued", function () {
            var _UploadFile = option.uploader.getFiles();
            if (_UploadFile.length > 0)
                option.uploader.removeFile(_UploadFile[_UploadFile.length - 1], true);
        });

        //图片加入队列,输入预览图像
        option.uploader.on('fileQueued', function (file) {

            // 创建缩略图
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            option.uploader.makeThumb(file, function (error, src) {
                if (error)
                    alert("图片无法预览!");
                else
                    option.image.attr('src', src);
            }, option.thumbnailWidth, option.thumbnailHeight);

            // progress 
            changeProgress(0);

            //上传按钮
            createUploadBtn("开始上传");
            $(option.pick.id).siblings().remove();
            $(option.pick.id).after(uploadBtn);
        });


        //错误信息
        option.uploader.on("error", function (handler) {
            switch (handler) {
                case "Q_EXCEED_NUM_LIMIT":
                    $.L.msgWarning("只能上传一张图片!");
                    break;
                case "F_EXCEED_SIZE":
                    $.L.msgWarning("图片大小不能超过1M!");
                    break;
                case "Q_TYPE_DENIED":
                    $.L.msgWarning("不支持的图片类型!");
                    break;
            }
        });

        //上传完成 [不管成功或失败都触发]
        option.uploader.on("uploadComplete", function (file) { });

        //上传成功
        option.uploader.on("uploadSuccess", function (file, info) {
            option.image.attr("src", info.fileName);
            $(_Obj).find('.infobox').text("上传成功").css("color", "green").fadeIn();
            $(_Obj).find('.infobox,.progress').fadeOut(3000);
            option.callback();
        });

        //上传出错
        option.uploader.on("uploadError", function (file, info) {
            changeProgress(0);
            $(_Obj).find(".infobox").text("上传失败").css("color", "red").fadeIn();
        });

        //进度条
        option.uploader.on("uploadProgress", function (file, percentage) {
            changeProgress(percentage);
        });
    }

})(jQuery);
对 web uploader 的封装

 

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public JsonResult UploadAvatar(HttpPostedFileBase file, string uploadtype)
        {
            // 图片路径
            string _path = string.Empty;

            if (string.IsNullOrEmpty(uploadtype))
            {
                throw new Exception("上传失败!");
            }
            else
            {
                // 允许上传的图片的类型
                List<string> _imagetype = new List<string>() { ".jpg", ".jpeg", ".bmp", ".png" };

                // 图片名称
                string _avatarname = string.Empty;

                // file是否存在
                if (file == null || file.ContentLength == 0)
                {
                    throw new Exception("上传失败!");
                }
                // file的大小
                else if (file.ContentLength > (1 * 1024 * 1024))
                {
                    throw new Exception("图片不大于1M!");
                }
                else
                {
                    string _extension = Path.GetExtension(file.FileName).ToLower();
                    if (!_imagetype.Contains(_extension))
                    {
                        throw new Exception("不支持的图片类型!");
                    }
                    else
                    {
                        EncryptHelper _eh = new EncryptHelper();
                        _avatarname = _eh.Md5(DateTime.Now.Ticks.ToString()) + _extension;
                        _path = Path.Combine(Server.MapPath("~/Images/UserAvatar/"), _avatarname);
                        file.SaveAs(_path);

                        _path = "/Images/UserAvatar/" + _avatarname;

                        switch (uploadtype)
                        {
                            case "avatar_userinfo":
                                //保存至数据库
                                break;
                            case "avatar_teacherinfo":
                                //保存至数据库
                                break;
                            case "avatar_studentinfo":
                                //保存至数据库
                                break;
                        }
                    }
                }

            }

            return Json(new { fileName = _path });
        }
Controller

 

posted @ 2016-08-04 14:26  十七玄月  阅读(902)  评论(0编辑  收藏  举报