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
相關文章
相關標籤/搜索