jQuery 自制上傳頭像插件-附帶Demo實例(ajaxfileupload.js第三彈)

這篇文章主要是對前兩篇關於ajaxfileupload.js插件的文章javascript

ASP.NET 使用ajaxfileupload.js插件出現上傳較大文件失敗的解決方法(ajaxfileupload.js第一彈)css

jQuery 關於ajaxfileupload.js插件的逐步解析(ajaxfileupload.js第二彈)html

的一個收關。可是最初也是由於想作這麼一個功能,一點一點的引起出了好多問題,不斷去學習,研究,才寫了這三篇。java

早些時候已經實現了上傳頭像的功能,可是代碼倒是零零散散的,有html,有jQuery還有c#,因此就決定把這個功能獨立出來,當個插件用會方便不少。而事實是在封裝成插件的過程當中,也學到了不少知識。jquery

下面給你們看一下界面:web

一、初始狀況下ajax

二、點擊上傳頭像,彈出選擇,預覽浮動框數據庫

三、選擇圖片json

四、肯定後,符合要求,會提示成功,不符合要求,也會作出相應的提示c#

五、預覽

六、肯定上傳

下面是部分代碼

js部分:

$.fn.extend({

    ShowTheFloatDiv: function (obj) {
        $(this).click(function () {
            $("body").find("*").not("div.float-outer").attr("disabled", "disabled");
            var $float = jQuery.CreateTheFloatDiv();
            $img_outer_obj = obj;
        });
    }

});

$.extend({
    CreateTheFloatDiv: function () {
        if ($(".float-outer").size() == 1) {
            return $(".float-outer");
        }

        var left_offset = ($(window).width() - 600) / 2;//顯示在瀏覽器窗口比較正的位置,看着比較舒服
        var top_offset = ($(window).height() - 278) / 3;

        var theFloatDivHtml = "<div class='float-outer' style='left:" + left_offset + "px;top:" + top_offset + "px;'>";
        theFloatDivHtml += "<div class='float-header float-border'>上傳頭像</div>";
        theFloatDivHtml += "<div class='float-content'>";
        theFloatDivHtml += "<div class='content-first-row'>文件名:";
        theFloatDivHtml += "<input type='text' id='tb_filename' style='width:350px;' readonly /> ";
        theFloatDivHtml += "<input type='button' id='btn_selectfile' value='選擇圖片' style='margin-left:-10px;' />";
        theFloatDivHtml += "<input type='file' id='btn_upload' name='btn_upload' style='display:none;' accept='.jpg,.bmp,.gif' />";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "<div class='content-second-row'>";
        theFloatDivHtml += "<span class='img-portrait' style='width:80px;'>圖片預覽:</span>";
        theFloatDivHtml += "<div class='img-portrait' style='padding-top:30px;'>";
        theFloatDivHtml += "<img src='' class='preview60' alt=''/>";
        theFloatDivHtml += "<span>60*60</span>";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "<div style='float:left;'>";
        theFloatDivHtml += "<img src='' class='preview120' alt=''/>";
        theFloatDivHtml += "<span>120*120</span>";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "<div class='float-footer float-border'>";
        theFloatDivHtml += "<input type='submit' value='肯定' id='btn_ok' />";
        theFloatDivHtml += "<input type='button' value='取消' id='btn_cancel' />";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "</div>";

        $("body").append(theFloatDivHtml);

        return $(".float-outer");
    }
});

var $img_outer_obj;
$(function () {

    //取消事件
    $("body").delegate("#btn_cancel", "click", function () {
        $(".float-outer").remove();
        $("body").find("*").removeAttr("disabled");
    });


    //選擇圖片事件
    $("body").delegate("#btn_selectfile", "click", function () {
        $("#btn_upload").trigger(e);
    });

    var e = jQuery.Event("click");

    $("body").delegate("#btn_upload", "click", function () {

    }).delegate("#btn_upload", "change", function () {
        var curPATH = getFilePath($(this).get(0));
        var fileName = curPATH.substring(curPATH.lastIndexOf("\\") + 1);
        var type = curPATH.substring(curPATH.lastIndexOf('.') + 1).toLowerCase();
        if (type == "jpg" || type == "gif" || type == "bmp") {
            $("input#tb_filename").val(fileName);
            if ($("input#tb_filename").val() == "") {
                alert("請先上傳文件!");
                return;
            }
            $.ajaxFileUpload
            (
                {
                    url: '/UploadPortrait.aspx', //用於文件上傳的服務器端請求地址,須要根據實際狀況進行修改
                    secureuri: false, //通常設置爲false
                    fileElementId: $("input#btn_upload").attr("id"), //文件上傳空間的id屬性  <input type="file" id="file" name="file" />          //$("form").serialize(),表單序列化。指吧全部元素的ID,NAME 等所有發過去
                    dataType: 'json', //返回值類型 通常設置爲json
                    complete: function () {//只要完成即執行,最後執行
                    },
                    success: function (data, status)  //服務器成功響應處理函數
                    {
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                if (data.error == "1001") {
                                }
                                else if (data.error == "1002") {
                                    $("input#tb_filename").val("");
                                    $(".preview60").attr("src", "");
                                    $(".preview120").attr("src", "");
                                }
                                alert(data.msg);
                                return;
                            } else {
                                alert(data.msg);
                            }
                        }
                        $(".preview60").attr("src", data.imgurl);
                        $(".preview120").attr("src", data.imgurl);

                    },
                    error: function (data, status, e)//服務器響應失敗處理函數
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
        else {
            alert("請選擇正確的圖片格式(.jpg|.gif|.bmp)");
        }
    });


    $("body").delegate("#btn_ok", "click", function () {
        $img_outer_obj.attr("src", $(".preview120").attr("src"));
        $(".float-outer").remove();
        $("body").find("*").removeAttr("disabled");
    });

    //移動浮動框
    var offset_left, offset_top, moveFlag;
    $("body").delegate(".float-header", "mousedown", function (e) {
        moveFlag = true;
        offset_left = e.pageX - $(this).offset().left;
        offset_top = e.pageY - $(this).offset().top;
        $("body").delegate(".float-header", "mousemove", function (e) {
            if (moveFlag) {
                $(".float-outer").css("left", e.pageX - offset_left + "px").css("top", e.pageY - offset_top + "px");
            }
        }).delegate(".float-header", "mouseup", function () {
            moveFlag = false;
        })
    })
});

C#部分:

由於上傳文件用到了ajax,須要先將圖片上傳到本地,這裏也算是一個比較糾結的事情吧,由於若是想預覽,除非用一些插件,不然使用的方法都得是先上傳,再預覽這樣。這種來者都要不拒的事,看起來比較流氓哈~~

        HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        string msg = string.Empty;
        string error = string.Empty;
        string imgurl = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (files.Count > 0)
            {
                if (System.IO.File.Exists(Server.MapPath("/UploadImages/") + files[0].FileName))
                {
                    msg = "圖片已存在";
                    error = "1001";
                    string res1 = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";
                    Response.Write(res1);
                    Response.End();
                    return;
                }
                if (files[0].ContentLength > 4 * 1024 * 1024)
                {
                    msg = "圖片大小不能超過4M";
                    error = "1002";
                    string res1 = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";
                    Response.Write(res1);
                    Response.End();
                    return;
                }
                try
                {
                    files[0].SaveAs(Server.MapPath("/UploadImages/") + System.IO.Path.GetFileName(files[0].FileName));
                }
                catch (System.IO.DirectoryNotFoundException)
                {
                }
                msg = " 上傳成功! 圖片大小爲:" + files[0].ContentLength + "K";
                imgurl = "/UploadImages/" + files[0].FileName;
                string res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";
                Response.Write(res);
                Response.End();
            }
        }

 

如何調用此插件

    <script type="text/javascript">
        $(function () {
            $("#btn_portrait").ShowTheFloatDiv($("#img_portrait"));
        })
        
    </script>

注意事項

必須在「上傳頭像」按鈕所在頁面引入如下幾個文件

UploadPortrait.css

ajaxfileupload.js

jquery-2.0.3.min.js(jQuery插件要求在1.4.2版本之上)

UploadPortrait.js

若是你們在使用過程當中出現問題,能夠先把前面相關的兩篇文章略讀一下,大概就能找到緣由了。

大體這個功能就是如上這樣,感興趣的朋友能夠從下面的地址下載Demo運行看看。此外想說的是,由於是頭像嘛,必定要存數據庫的,可是在Demo裏我並無寫,這個東西就是看你們想怎麼實現了,要是個人話,由於以前預覽都要將圖片存到本地,因此若是存數據庫的話,固然是會存圖片的url了,那這樣就比較好辦了。

總的來講,要比想像中的快些完成了這個插件,功能卻是達到了本身的預期,可是界面來講,還有很長的一段路要走。第一次寫jQuery插件,不少東西都不太專業,但願大牛們能多多給予指正和幫助。

Demo下載地址:http://files.cnblogs.com/zhouhongyu1989/uploadportrait%E4%B8%8A%E4%BC%A0%E5%A4%B4%E5%83%8FDemo.rar

 

關於上傳的Demo補充內容:

 

上傳的demo有兩個問題須要說明一下,但願下載的朋友可以注意到,並流暢運行。

 

一、由於demo是ASP.NET項目,因此你們如想正常運行,須要在本地新建一個web項目,把我上傳的uploadportrait.csproj這個文件添加進去。下次我會直接打包一個完整的web項目再上傳,此次沒作好但願你們給予諒解。另,我開發的時候Visual Studio版本爲2010,這個望你們注意一下。

 

二、在調用插件的代碼部分,demo裏寫的是

    <script type="text/javascript">
        $(function () {
            $("#btn_portrait").ShowTheFloatDiv($("#img_portrait"));
        })
        
    </script>

應該把$(img_portrait)改爲$("#img_portrait"),這個也是本身的失誤,下回會注意。

 

補充:

jQuery 關於IE9上傳文件沒法進入後臺問題的緣由及解決辦法(ajaxfileupload.js第四彈)

相關文章
相關標籤/搜索