代码
<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); } }
还有一种方法:Request.Files,这个会得到所有页面上的file上传控件。
HttpPostedFileBase file = Request.Files[0];如果有多个file,循环获得。
这样在Action中就不需要加多一个HttpPostedFileBase参数了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】