ASP.Net MVC3 圖片上傳詳解(form.js,bootstrap)

     圖片上傳的插件不少,但不少時候仍是不能切合咱們的需求,我這裏給你們分享個我用一個form,file實現上傳四張圖片的小demo。徹底是用jquery先後交互,沒有用插件。css

     最終效果圖以下:html

     

    玩過花田人可能有些眼熟,原型就是來自於花田網中的圖片上傳。 jquery

    引用的腳本有:ajax

  <script src="../../Scripts/jquery-ui-1.9.2.custom.min.js"></script>
    <script src="../../Scripts/jquery-1.8.3.js"></script>
    <link href="../../Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <script src="../../Content/bootstrap/js/bootstrap.min.js"></script>  <script src="../../Content/JS/form.js"></script>
View Code

    基本思路:用戶點擊相關div觸發file元素打開瀏覽框----》用setInterval不斷檢測file文件是否選中文件---》選中以後觸發form自動提交到後臺---》後臺將文件存儲到臨時文件夾返回圖片在臨時文件夾的地址---》窗口提示上傳功能並預覽圖片---》用戶點擊發布---》後臺保存圖片(移動到指定文件夾,並存入數據庫)數據庫

   整個過程form和file都是隱藏的。另外的效果bootstrap

  1. 開始的時候只顯示一個上傳框,前一個上傳完成後,顯示下一個上傳框。並老是顯示在最後面。瀏覽器

  2. 有圖片的時候才能提交和輸入描述。session

  3.上傳成功以後,刪除後才能再次上傳。app

  Html+csside

      .uploadbox {
            float: left;width: 115px;height: 115px;
            background-color: #eeeeee;
            margin-right: 10px;color: white;text-align: center;cursor: pointer;
            position: relative;display: none;
        }
        .uploadbox:hover {
              background-color: #b4b4b4;
        }
       .stt{ font-size: xx-small;display: block;}
       .add{  vertical-align: baseline;display: block;height: auto;font-size: 8em; height: 40px;padding: 10px;margin-top: 30px}
      .imgcontainer{ width: 100%;height: 100%}  .imgcontainer img{ max-height: 115px;max-width: 115px;}
        .inputdiv{ clear: both;display: block;padding-top: 10px;}
        #Remark{ width:478px;}
       .infospan{display: none; height: 20px;position: absolute;bottom: 0;right: 0;width: 100%;background-color: #00bfff;z-index: 1;clear: both;opacity: 0.8;}
       .closespan{display: none; position: absolute;right: -7px;top: -7px;width: 14px;height: 14px;border-radius: 7px;background-color: white;border: 1px gainsboro solid;color: gray;
           font-weight: bold;font-size: medium;
           line-height: 16px;
       }   .closespan:hover{ color: red;}
       #imgupload form{ display: none;}       
       .imguploadmessage{ font-size: small;color: green;float: left;margin-left: 10px;}
       .carclose{ cursor: pointer;  
           background-color: white;opacity: 1;
           position: absolute;z-index: 99;top:0px;right: -40px;
           width: 40px;height:40px;border-radius: 20px;text-align: center;
           line-height: 40px;font-size: 2em;color: gray;
       }.carclose:hover{ color: green;background-color: #eeeeee}
View Code
  <div id="imgupload" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4>上傳圖片</h4>  
        </div>
        <div class="modal-body">
            <div class="uploadbox" data-count="0" style="display: inline;">
                <span class="closespan" title="刪除照片">&times;</span>
                <div class="imgcontainer">
                    <div class="add">+</div>
                    <div class="stt">點擊上傳</div>
                </div>
                <span class="infospan">
                    <img src='../../Content/Photos/loading.gif' />正在上傳...</span>
            </div> 
            <div class="uploadbox" data-count="0"  >
                <span class="closespan" title="刪除照片">&times;</span>
                <div class="imgcontainer">
                    <div class="add">+</div>
                    <div class="stt">點擊上傳</div>
                </div>
                <span class="infospan"> <img src='../../Content/Photos/loading.gif' />正在上傳...</span>
            </div> 
            <div class="uploadbox"data-count="0" >
                <span class="closespan" title="刪除照片">&times;</span>
                <div class="imgcontainer">
                    <div class="add">+</div>
                    <div class="stt">點擊上傳</div>
                </div>
                <span class="infospan"> <img src='../../Content/Photos/loading.gif' />正在上傳...</span>
            </div> 
            <div class="uploadbox"data-count="0"  >
                <span class="closespan" title="刪除照片">&times;</span>
                <div class="imgcontainer">
                    <div class="add">+</div>
                    <div class="stt">點擊上傳</div>
                </div>
                <span class="infospan"> <img src='../../Content/Photos/loading.gif' />正在上傳...</span>
            </div> 
            <div class="inputdiv"><input type="text" disabled="disabled" id="Remark" name="Remark" placeholder="補充說明下~"/></div>
        </div>
            <div class="modal-footer">
             上傳大小在8k-10M之間 <span class="imguploadmessage"></span>
              <button class="btn btn-success "  disabled="disabled"   id="imgsubmit">發佈</button>
              <form action="/User/UpLoadPhoto" method="POST" enctype="multipart/form-data" name="ImgForm" id="ImgForm">
              <input type="file" name="file" id="imgFlie"  required="required" />
              <input type="submit" name="subt" value="上傳圖片" />
              </form>
            </div>
   
    </div>
View Code

Jquery:

 //圖片上傳-------------------------------------imgupload---------------------

    var imgbox = {};//用來獲取當前點擊的 uploadbox 
    var childs = $(".imgcontainer:eq(0)").html();// 先保存內部元素,上傳完成以後方便恢復到最初狀態
    $(".uploadbox").click(function () {
        var tag = $(this).attr("data-count");//用來判斷是否已經含有照片
        if (tag == "1") return false;
        $("#imgFlie").click();
        imgbox = $(this);
        var stm1 = setInterval(function () {
            var imgstr = $("#imgFlie").val(); //檢測file元素是否已經含有文件
            if (imgstr != "") {
                clearInterval(stm1);
                $("#ImgForm input[type='submit']").click();
            }
        }, 500);
        return false;
    });

    // 取消照片
    $(".closespan").click(function (e) {
        e.stopPropagation();
        var sum = $(".uploadbox img").length;
        // 保證有一個框可讓用戶再次選擇 須要顯示childs 設置data-count屬性 必要的再隱藏
        var imgsrc = $(this).next().find("img").attr("src");
        $(this).next().html("").append(childs);
        // 隱藏關閉和成功提示
        $(this).hide();
        $(this).siblings(".infospan").hide();
        $(this).parent().attr("data-count", 0).insertBefore($(".inputdiv"));;

        if (sum < 4) {//說明此時是有一個再準備狀態,這個能夠直接作刪除處理 
            // 設置data-count 並隱藏父級
            $(this).parent().hide();
            //須要移位 保證準備狀態的老是在最後一個  
        }
        // 清除session 減小一個字符串
        if (imgsrc != undefined) {
            $.post("/User/DeleteImg", { str: imgsrc }, function () {

            });
        }
        if (sum == 1) {
            $('#Remark,#imgsubmit').attr("disabled", "disabled");// 說明這個時候尚未圖片上傳,因此要禁止發佈鍵和描述框
        }

    });

    //----------上傳圖片---------------------------------------------
    $("#imgsubmit").click(function () {
        var imgcontent = $.trim($("#Remark").val());
        $.post("/User/SaveImgs", { content: imgcontent }, function (data) {
            if (data == 1) {
                //清除content
                $(".imgcontainer").html(childs);
                //隱藏進度條和關閉鍵
                $(".closespan,.infospan").hide();
                $(".imguploadmessage").html("上傳成功!");
                //禁止輸入框和提交按鈕
                $('#Remark,#imgsubmit').attr("disabled", "disabled");
                //去掉data-count 屬性 顯示第一個;
                $(".uploadbox").attr("data-count", 0).hide().eq(0).show();
                //清空
                $("#Remark").val("");
                var stt = setTimeout(function () {
                    $("#imgupload").modal('hide');
                    $(".imguploadmessage").html("");
                    clearTimeout(stt);
                }, 1000);
            }
        });
    });

    $('#ImgForm').ajaxForm({//用到form.js 提交form 
        beforeSend: function () {
            imgbox.find(".infospan").show();//顯示正在上傳...
        },
        success: function (data) {
            $("#imgFlie").val("");//
            imgbox.find(".imgcontainer").html(data);//.hide()
            var img = imgbox.find(".imgcontainer").find("img").attr("src");
            if (img != undefined) {//表示上傳成功
                //解禁
                $('#Remark').removeAttr("disabled");
                $('#imgsubmit').removeAttr("disabled");
                imgbox.find(".infospan,.closespan").show();
                imgbox.find(".infospan").html("上傳成功!");
                //顯示下一個
                //imgbox.next().show();
                $(".uploadbox:hidden").eq(0).show();

                imgbox.attr("data-count", "1");
            } else {
                imgbox.find(".infospan,.closespan").hide();
            }
            // alert(img);
        }, complete: function (xhr) {
            $("#imgFlie").val("");
        }
    });

 後臺controller的代碼

   [HttpPost]
        public void UpLoadPhoto(HttpPostedFileBase file)
        {
            var res = CheckImg(file);
            if (res == "ok")
            {
                var fileName = file.FileName;//Path.GetExtension() 也許能夠解決這個問題,先無論了。
                var pathtemp = Path.Combine(Server.MapPath("../Content/TempFile/"), fileName);//先存入臨時文件夾
                var scrtemp = Path.Combine("../../Content/TempFile/", fileName);//圖片展現的地址

                var list = Session["Imgscr"] as List<string>;
                var slist = Session["ImgServerscr"] as List<string>;
                if (list != null)
                {
                    list.Add(scrtemp);
                }
                else
                {
                    list = new List<string> { scrtemp };
                    Session["Imgscr"] = list;
                }
                if (slist != null)
                {
                    slist.Add(pathtemp);
                }
                else
                {
                    slist = new List<string> { pathtemp };
                    Session["ImgServerscr"] = slist;
                }

                file.SaveAs(pathtemp);
                Response.Write("<img src='../../Content/TempFile/" + fileName + "' /> ");
            }
            else
            {
                Response.Write(res);
            }
        }

        /// <summary>
        /// 刪除預覽中的照片
        /// </summary>
        /// <param name="str">這個str 已是處理過的,不是以前上傳的圖片名稱</param>
        public void DeleteImg(string str)
        {
            //刪除地址 刪除文件
            var list = Session["Imgscr"] as List<string>;
            if (list == null) return;
            var index = list.IndexOf(str);
            var slist = Session["ImgServerscr"] as List<string>;
            if (slist != null && index != -1)
            {
                var imgone = slist[index];
                if (imgone != null)
                {
                    var img = new FileInfo(imgone);
                    if (img.Exists) img.Delete();
                }
            }
            list.Remove(str);
        }

        private string CheckImg(HttpPostedFileBase file)
        {
            if (file == null) return "圖片不能空!";
            if (file.ContentLength / 1024 > 8000)
            {
                return "圖片太大";
            }
            if (file.ContentLength / 1024 < 10)
            {
                return "圖片過小!";
            }
            var image = GetExtensionName(file.FileName).ToLower();
            if (image != ".bmp" && image != ".png" && image != ".gif" && image != ".jpg" && image != ".jpeg")// 這裏你本身加入其餘圖片格式,最好所有轉化爲大寫再判斷,我就偷懶了
            {
                return "格式不對";
            }

            var scrtemp = Path.Combine("../../Content/TempFile/", file.FileName);//圖片展現的地址
            var list = Session["Imgscr"] as List<string>;
            if (list != null && list.Find(n => n == scrtemp) != null)
            {
                return "一樣的照片已經存在!";
            }

            return "ok";
        }

        public JsonResult SaveImgs(string content)
        {
            var uid = CheckValid();
            if (_uName == null) _uName = GetUserNameById(uid);

            string path = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), _uName, "Photos", "ImgBox");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var list = Session["Imgscr"] as List<string>;
            var finallist = new List<string>();
            if (list == null) return Json(0);
            foreach (var str in list)
            {
                var scrtemp1 = Server.MapPath(str.Substring(3, str.Length - 3));//去掉第一個../
                var img = new FileInfo(scrtemp1);
                if (img.Exists)
                {
                    var image = GetExtensionName(img.Name);
                    //處理照片名稱
                    var imgname = string.Format("{0:yyyMMdd}", DateTime.Now).Replace("/", "") + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture).Substring(7, 11) + image;
                    var scrdestination = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), _uName, "Photos", "ImgBox", imgname);
                 
                    var scrshow = Path.Combine(("../../Content/UploadFiles/"), _uName, "Photos", "ImgBox", imgname);
                    finallist.Add(scrshow);
                    //移動照片
                    img.MoveTo(scrdestination);
                    //存入imgbox
                    var box = new Iamgbox
                    {
                        ActionTime = DateTime.Now,
                        BoxName = _uName,
                        ImgUrl = scrshow,
                        IsValid = true, //默認是正規合適的圖片 不合適在檢舉
                        PraiseCount = 0,
                        Remark = content,
                        UserId = uid,
                        VisitCount = 0,
                    };
                    LoveDb.Add(box);
                };
            }
            if (finallist.Count() != 0)
            {
                var sbstr = new StringBuilder("<br/><div class='imgtigger'>");
                foreach (var str in finallist)
                {
                    sbstr.Append("<img src='" + str + "' />");
                }
                sbstr.Append("</div>");
                var state = new State
                {
                    ActionTime = DateTime.Now,
                    Content = (content == "" ? string.Format("剛剛上傳了{0}張照片:", finallist.Count) : content)+sbstr,
                    PraiseCount = 0,
                    StateType = StateType.Image.ToString(),
                    UserId = uid
                };
                LoveDb.Add(state);
                Session.Remove("Imgscr");
                Session.Remove("ImgServerscr");
            }
              

            return Json(1);
        }
   public string GetExtensionName(string fileName)
        {
            if (fileName.LastIndexOf("\\", StringComparison.Ordinal) > -1)//在不一樣瀏覽器下,filename有時候指的是文件名,有時候指的是全路徑,全部這裏要要統一。
            {
                fileName = fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1);//IndexOf 有時候會受到特殊字符的影響而判斷錯誤。加上這個就糾正了。
            }
            return Path.GetExtension(fileName.ToLower());
        }
View Code

 到這,這個過程就完成了,但願對你有幫助。

 Demo 下載地址: http://download.csdn.net/detail/stoneniqiu/6581841 

 沒有積分的留個郵箱吧。

相關文章
相關標籤/搜索