MVC3下异步表单提交上传图片实现

由于项目需要【任何一个人都能上传不定张图片】,这两天就在写这个功能。现在写完了,记录下。

语言:C#

环境:MVC3 + EF4 

所需插件下载地址:http://download.csdn.net/detail/tl110110tl/8248099

所需数据库表如下图:



插件参考:http://www.cnblogs.com/china-li/archive/2012/12/12/2800144.html


html代码:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>AddSkin</title>
    <style type="text/css">
        .
        {
            margin: 0;
            padding: 0;
        }
        .skinType
        {
            margin: 10px;
            float: left;
            width: 150px;
            height: 100px;
            border: 2px solid blue;
            font-size: 38px;
            color: yellow;
            text-align: center;
            line-height: 100px;
            cursor:pointer;
        }
        .clear
        {
            margin: 0;
            padding: 0;
            clear: both;
        }
    </style>
    <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.form.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".skinType").click(function () {
                var mingzi = $(this).html();
                var typeid = $(this).attr("typeid");
                $("#Mingzi").html(mingzi);
                $("#TypeID").val(typeid);
                $("#div1").html("");
                var TypeID = $("#TypeID").val();
                $.ajax({
                    type: "post",
                    cache: false,
                    data: { "TypeID": TypeID },
                    url: "/Skin/GetImgUrl",
                    success: function (msg) {
                        var err = msg;
                        err = err.substring(0, 5);
                        //alert(err);
                        if (err != "error") {
                            showImgs(msg);
                        }
                    },
                    error: function () {
                        alert("出了点小错误,暂时看不到 " + $("#Mingzi") + " 图片信息");
                    }
                });
            });

            var options = {
                target: '#div1',   // target element(s) to be updated with server response 
                //beforeSubmit: showRequest,  // pre-submit callback 
                success: showResponse  // post-submit callback 
            };

            // bind to the form's submit event 
            $('#myForm').submit(function () {
                $("#div1").html("正在上传..");
                $(this).ajaxSubmit(options);
                return false;
            });
        });
        function showResponse() {
            var div1 = $("#div1").html();
            div1 = div1.substring(0, 5);
            //alert(div1);
            if (div1 != "error") {
                //把图片们都显示出来
                showImgs();
            }
        }
        function showImgs(urls) {
            var strIds = urls;
            if (typeof (urls) == "undefined") {
                //如果传进来的urls是空的,那么证明需要从div1里面拿数据
                strIds = $("#div1").html();
            }
            if (strIds.length < 1) {
                $("#imgContent").html("");
                return;
            }
            //遍历并拼接<img alt="" src="/Home/Image" />标签
            var strs = new Array();
            strs = strIds.split(",");
            var htms = "";
            var sts = new Array();
            for (var i = 0; i < strs.length; i++) {
                sts = strs[i].split("|");
                htms += "<img alt=\""+sts[1]+"\" src=\"" + sts[0] + "\" />";
                $("#imgContent").html(htms);
            }
        }
    </script>
</head>
<body>
    <div>
        <div class="skinType" typeid="1">
            类别1
        </div>
        <div class="skinType" typeid="2">
            类别2
        </div>
        <div class="skinType" typeid="3">
            类别3
        </div>
        <div class="skinType" typeid="4">
            类别4
        </div>
        <div class="clear">
        </div>
        <hr color="gray" />
        <div>
            为:<span id="Mingzi" style="color:red;font-size:22px;"></span>添加skin
            <form id="myForm" action="/Skin/AddImg" method="post" enctype="multipart/form-data">
            <input type="file" name="upfile" /><br />
            <input type="hidden" id="TypeID" name="TypeID" />
            <input type="submit" value="确认上传" />上传文件最大为<span style="color: Blue;">8MB</span>
            </form>
            <hr />
            <div id="div1" style="color: Red;">
            </div>
            <div id="imgContent">
            </div>
        </div>
    </div>
</body>
</html>


后台对应的controller


namespace SGS.Mainproto.Controllers
{
    public class SkinController : Controller
    {
        //
        // GET: /Skin/
        IBLL.ISkinBLL _skinBLL = new BLL.SkinBLL();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 添加 skin
        /// URL:/Skin/AddSkin
        /// </summary>
        public ActionResult AddSkin()
        {
            return View();
        }

        /// <summary>
        /// 添加 图片
        /// URL:/Skin/AddImg
        /// </summary>
        [HttpPost]
        public ActionResult AddImg()
        {
            string TypeID = Request["TypeID"];
            int typeId;
            if (!int.TryParse(TypeID, out typeId))
            {
                return Content("error_typeID错误");
            }

            HttpPostedFileBase file = Request.Files[0];
            if (file.ContentLength > 0 && file.ContentLength / 1024 < 10000)
            {
                //得到文件的扩展名
                string ext = System.IO.Path.GetExtension(file.FileName);
                if (ext.ToLower() == ".jpg" || ext.ToLower() == ".png" || ext.ToLower() == ".gif")
                {
                    string datePath = DateTime.Now.ToString("yyyy/MM/dd");//时间路径
                    string oneFilePath = Server.MapPath("/ImageUp/" + datePath);//时间本地路径
                    if(!System.IO.Directory.Exists(oneFilePath))//创建本地目录
                    {
                        System.IO.Directory.CreateDirectory(oneFilePath);
                    }
                    string filename = Guid.NewGuid().ToString() + ext;//唯一保存文件名
                    string finallFilePath = oneFilePath + "/" + filename;//最终本地保存路径
                    Model.Skin skin = new Model.Skin();
                    skin.SkinType = typeId.ToString();
                    skin.SkinName = file.FileName;
                    skin.SkinURL = "/ImageUp/" + datePath + "/" + filename;
                    _skinBLL.AddEntity(skin);
                    file.SaveAs(finallFilePath);
                    var skinUrl = _skinBLL.LoadEntitys(s=>s.SkinType==TypeID).OrderByDescending(s=>s.ID).Select(s=>s.SkinURL+"|"+s.SkinName);
                    string res = "";
                    foreach (string item in skinUrl)
                    {
                        res += item + ",";
                    }
                    res = res.TrimEnd(',');
                    return Content(res);
                }
                else
                {
                    return Content("error_不是图片文件");
                }
            }
            else
            {
                return Content("error_文件为空或者超过了8M");
            }
        }
        [HttpPost]
        public ActionResult GetImgUrl()
        {
            string TypeID = Request["TypeID"];
            if (string.IsNullOrEmpty(TypeID))
            {
                return Content("error_typeID为空");
            }
            var skinUrl = _skinBLL.LoadEntitys(s => s.SkinType == TypeID).OrderByDescending(s => s.ID).Select(s => s.SkinURL + "|" + s.SkinName);
            string res = "";
            foreach (string item in skinUrl)
            {
                res += item + ",";
            }
            res = res.TrimEnd(',');
            return Content(res);
        }
    }
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。