jQuery 自製上傳頭像外掛程式-附帶Demo執行個體(ajaxfileupload.js第三彈)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   使用   java   ar   

這篇文章主要是對前兩篇關於ajaxfileupload.js外掛程式的文章

《ASP.NET 使用ajaxfileupload.js外掛程式出現上傳較大檔案失敗的解決方案(ajaxfileupload.js第一彈)》

《jQuery 關於ajaxfileupload.js外掛程式的逐步解析(ajaxfileupload.js第二彈)》

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

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

下面給大家看一下介面:

1、初始情況下

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

3、選擇圖片

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

5、預覽

6、確定上傳

下面是部分代碼

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

jQuery 自製上傳頭像外掛程式-附帶Demo執行個體(ajaxfileupload.js第三彈)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.