ASP.Net MVC3 图片上传详解(form.js,bootstrap)

     图片上传的插件很多,但很多时候还是不能切合我们的需求,我这里给大家分享个我用一个form,file实现上传四张图片的小demo。完全是用jquery前后交互,没有用插件。

     最终效果图如下:

     ASP.Net MVC3 图片上传详解(form.js,bootstrap)

    玩过花田人可能有些眼熟,原型就是来自于花田网中的图片上传。 

    引用的脚本有:

  <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都是隐藏的。另外的效果

  1. 开始的时候只显示一个上传框,前一个上传完成后,显示下一个上传框。并总是显示在最后面。

  2. 有图片的时候才能提交和输入描述。

  3.上传成功之后,删除后才能再次上传。

  Html+css

      .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 

 没有积分的留个邮箱吧。

 

你可能感兴趣的:(bootstrap)