码迷,mamicode.com
首页 > Web开发 > 详细

MVC上传文件

时间:2016-06-15 20:43:55      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

页面代码:

@using (Html.BeginForm("ModifySave", "ArticlesInfo", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
@Html.TextBoxFor(model => model.Title, new { @class = "boxtext" })
<br />
@Html.TextAreaFor(model => model.Contents, new { cols = "50", rows = "20", sign = "Contents" })
<br /> <input type="file" name="Img" class="boxtext" />
<br /> <input type="submit" value="保存" class="boxbut" /> }

  

后台代码:

[HttpPost]
        [ValidateInput(false)]
        public ActionResult ModifySave(Models.ArticlesInfo data, HttpPostedFileBase Img)
        {
            Models.ArticlesInfo model = db.ArticlesInfos.Single(c => c.ID == data.ID);
            model.Title = data.Title;
            model.Contents = data.Contents;
            if (Img != null && Img.ContentLength > 0)
            {
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetExtension(Img.FileName);
                string filePath = Server.MapPath("~/UploadFile/") + fileName;
                Img.SaveAs(filePath);
                model.Img = "/UploadFile/" + fileName;
            }
            db.SaveChanges();
            return RedirectToAction("Modify", new { id = model.ID, tid = model.TypeID });
        }

  注意:参数列表中的  HttpPostedFileBase Img,这个 Img 需要和页面中Html上传控件的name属性一样。

 

MVC上传文件

标签:

原文地址:http://www.cnblogs.com/xsj1989/p/5588603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!