溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2020-07-19 02:49:39 來(lái)源:網(wǎng)絡(luò) 閱讀:8040 作者:我不會(huì)抽煙 欄目:web開(kāi)發(fā)

這篇文章主要是對(duì)前兩篇關(guān)于ajaxfileupload.js插件的文章

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

《jQuery 關(guān)于ajaxfileupload.js插件的逐步解析(ajaxfileupload.js第二彈)》

的一個(gè)收關(guān)。但是最初也是因?yàn)橄胱鲞@么一個(gè)功能,一點(diǎn)一點(diǎn)的引發(fā)出了好多問(wèn)題,不斷去學(xué)習(xí),研究,才寫(xiě)了這三篇。

早些時(shí)候已經(jīng)實(shí)現(xiàn)了上傳頭像的功能,但是代碼卻是零零散散的,有html,有jQuery還有c#,所以就決定把這個(gè)功能獨(dú)立出來(lái),當(dāng)個(gè)插件用會(huì)方便很多。而事實(shí)是在封裝成插件的過(guò)程中,也學(xué)到了很多知識(shí)。

下面給大家看一下界面:

1、初始情況下

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

2、點(diǎn)擊上傳頭像,彈出選擇,預(yù)覽浮動(dòng)框

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

3、選擇圖片

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

4、確定后,符合要求,會(huì)提示成功,不符合要求,也會(huì)做出相應(yīng)的提示

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

5、預(yù)覽

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

6、確定上傳

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

下面是部分代碼

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=';'>圖片預(yù)覽:";
        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("請(qǐng)先上傳文件!");
                return;
            }
            $.ajaxFileUpload
            (
                {
                    url: '/UploadPortrait.aspx', //用于文件上傳的服務(wù)器端請(qǐng)求地址,需要根據(jù)實(shí)際情況進(jìn)行修改
                    secureuri: false, //一般設(shè)置為false
                    fileElementId: $("input#btn_upload").attr("id"), //文件上傳空間的id屬性  <input type="file" id="file" name="file" />          //$("form").serialize(),表單序列化。指吧所有元素的ID,NAME 等全部發(fā)過(guò)去
                    dataType: 'json', //返回值類(lèi)型 一般設(shè)置為json
                    complete: function () {//只要完成即執(zhí)行,最后執(zhí)行
                    },
                    success: function (data, status)  //服務(wù)器成功響應(yīng)處理函數(shù)
                    {
                        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)//服務(wù)器響應(yīng)失敗處理函數(shù)
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
        else {
            alert("請(qǐng)選擇正確的圖片格式(.jpg|.gif|.bmp)");
        }
    });


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

    //移動(dòng)浮動(dòng)框
    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#部分:

因?yàn)樯蟼魑募玫搅薬jax,需要先將圖片上傳到本地,這里也算是一個(gè)比較糾結(jié)的事情吧,因?yàn)槿绻腩A(yù)覽,除非用一些插件,否則使用的方法都得是先上傳,再預(yù)覽這樣。這種來(lái)者都要不拒的事,看起來(lái)比較流氓哈~~

        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 = "圖片大小不能超過(guò)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();
            }
        }

如何調(diào)用此插件

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

注意事項(xiàng)

必須在“上傳頭像”按鈕所在頁(yè)面引入以下幾個(gè)文件

UploadPortrait.css

ajaxfileupload.js

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

UploadPortrait.js

如果大家在使用過(guò)程中出現(xiàn)問(wèn)題,可以先把前面相關(guān)的兩篇文章略讀一下,大概就能找到原因了。

大致這個(gè)功能就是如上這樣,感興趣的朋友可以從下面的地址下載Demo運(yùn)行看看。此外想說(shuō)的是,因?yàn)槭穷^像嘛,一定要存數(shù)據(jù)庫(kù)的,但是在Demo里我并沒(méi)有寫(xiě),這個(gè)東西就是看大家想怎么實(shí)現(xiàn)了,要是我的話,因?yàn)橹邦A(yù)覽都要將圖片存到本地,所以如果存數(shù)據(jù)庫(kù)的話,當(dāng)然是會(huì)存圖片的url了,那這樣就比較好辦了。

總的來(lái)說(shuō),要比想像中的快些完成了這個(gè)插件,功能倒是達(dá)到了自己的預(yù)期,但是界面來(lái)說(shuō),還有很長(zhǎng)的一段路要走。第一次寫(xiě)jQuery插件,很多東西都不太專(zhuān)業(yè),希望大牛們能多多給予指正和幫助。

Demo下載地址:http://down.51cto.com/data/1871944


關(guān)于上傳的Demo補(bǔ)充內(nèi)容:

上傳的demo有兩個(gè)問(wèn)題需要說(shuō)明一下,希望下載的朋友能夠注意到,并流暢運(yùn)行。

1、因?yàn)閐emo是ASP.NET項(xiàng)目,所以大家如想正常運(yùn)行,需要在本地新建一個(gè)web項(xiàng)目,把我上傳的uploadportrait.csproj這個(gè)文件添加進(jìn)去。下次我會(huì)直接打包一個(gè)完整的web項(xiàng)目再上傳,這次沒(méi)做好希望大家給予諒解。另,我開(kāi)發(fā)的時(shí)候Visual Studio版本為2010,這個(gè)望大家注意一下。

2、在調(diào)用插件的代碼部分,demo里寫(xiě)的是

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

應(yīng)該把$(img_portrait)改成$("#img_portrait"),這個(gè)也是自己的失誤,下回會(huì)注意。


補(bǔ)充:

《jQuery 關(guān)于IE9上傳文件無(wú)法進(jìn)入后臺(tái)原因及解決辦法(ajaxfileupload.js第四彈)》




向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI