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

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

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

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

的一個收關。但是最初也是因爲想做這麼一個功能,一點一點的引發出了好多問題,不斷去學習,研究,才寫了這三篇。

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

下面給大家看一下界面:

1、初始情況下

wKioL1QPqAWjwLmCAAFKoBuNgKs619.jpg

2、點擊上傳頭像,彈出選擇,預覽浮動框

wKiom1QPqA7g4NfwAAGbvTRIVAQ305.jpg

3、選擇圖片

wKioL1QPqDOSDOAOAANIt3_6m64414.jpg

4、確定後,符合要求,會提示成功,不符合要求,也會做出相應的提示

wKioL1QPqFfA84n9AAH1a3wzRdI173.jpg

5、預覽

wKioL1QPqGujorJ_AAH9eM8WkqY726.jpg

6、確定上傳

wKioL1QPqH7wwSOpAAF4NCP95MA463.jpg

下面是部分代碼

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=';' 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=';'>圖片預覽:";
        theFloatDivHtml += "<div class='img-portrait' style='padding-top:30px;'>";
        theFloatDivHtml += "<img src='' class='preview60' alt=''/>";
        theFloatDivHtml += "<span>60*60";
        theFloatDivHtml += "</div>";
        theFloatDivHtml += "<div style='float:left;'>";
        theFloatDivHtml += "<img src='' class='preview120' alt=''/>";
        theFloatDivHtml += "<span>120*120";
        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://down.51cto.com/data/1871944


關於上傳的Demo補充內容:

上傳的demo有兩個問題需要說明一下,希望下載的朋友能夠注意到,並流暢運行。

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

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

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

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


補充:

jQuery 關於IE9上傳文件無法進入後臺原因及解決辦法(ajaxfileupload.js第四彈)




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章