首页 > 代码库 > MVC上传文件
MVC上传文件
代码
<form class="cmxform form-horizontal tasi-form" id="submitForm" method="POST" action="Add" novalidate="novalidate" enctype="multipart/form-data"> @{ if (!ViewData.ModelState.IsValid) { <div class="alert alert-danger alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> @string.Format("操作失败:{0}", ViewData.ModelState["Error"].Errors[0].ErrorMessage) </div> } } <div class="form-group "> @Html.LabelFor(item => item.Name, new { @class = "control-label col-lg-2" }) <div class="col-lg-10"> @Html.TextBoxFor(item => item.Name, new { @class = "form-control"}) </div> </div> <div class="form-group "> @Html.LabelFor(item => item.LinkUrl, new { @class = "control-label col-lg-2" }) <div class="col-lg-10"> @Html.TextBoxFor(item => item.LinkUrl, new { @class = "form-control" }) </div> </div> <div class="form-group "> @Html.LabelFor(item => item.Img, new { @class = "control-label col-lg-2" }) <div class="col-lg-10"> <input type="file" name="file" class="form-control" /> </div> </div> <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <button class="btn btn-success" type="submit">保存</button> <button class="btn btn-default" type="button" onclick="window.history.go(-1);">返回</button> </div> </div> </form>
注意:form里要加入 enctype="multipart/form-data",说明有文件要提交。
后台对应的要加入HttpPostedFileBase file, file 对应的是html中的上传控件的name属性。
后台:
[HttpPost] public ActionResult Add(Service.Dto.BannerInfoDto dto, HttpPostedFileBase file) { string fileName = ""; if (file == null) { ModelState.AddModelError("Error", "请选择图片 .jpg/.png/.gif"); return View(dto); } if (file != null) { string fileExt = Path.GetExtension(file.FileName).ToLower(); if (!".jpg/.png/.gif".Contains(fileExt)) { ModelState.AddModelError("Error", "图片格式不正确 .jpg/.png/.gif"); return View(dto); } fileName = "~/UploadFile/BannerInfo/" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt; string serPath = Server.MapPath(fileName); try { file.SaveAs(serPath); } catch (Exception ex) { ModelState.AddModelError("Error", "上传异常:" + ex.Message); return View(dto); } } Domain.RL_BannerInfo model = new Domain.RL_BannerInfo(); model.LinkUrl = dto.LinkUrl; model.Name = dto.Name; model.Img = fileName; bool result = BannerInfoManage.Save(model); ; if (result) { return RedirectToAction("Manage"); } else { ModelState.AddModelError("Error", "保存失败"); return View(dto); } }
大概就是这样
MVC上传文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。