ASP.NET MVC 4 C#HttpPostedFileBase,如何存储文件
模型
public partial class Assignment { public Assignment() { this.CourseAvailables = new HashSet<CourseAvailable>(); } public string AssignmentID { get; set; } public Nullable<System.DateTime> SubmissionDate { get; set; } public string Status { get; set; } public Nullable<decimal> Mark { get; set; } public string Comments { get; set; } public string FileLocation { get; set; } public virtual ICollection<CourseAvailable> CourseAvailables { get; set; } }}
调节器
public ActionResult Create(Assignment assignment) { if (ModelState.IsValid) { db.Assignments.Add(assignment); db.SaveChanges(); return RedirectToAction("Index"); } return View(assignment); }
视图
<div class="editor-field"> <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%> <%: Html.ValidationMessageFor(model => model.FileLocation) %> </div>
如果我想将文件存储到服务器/path文件夹和数据库中,我如何存储文件我只想存储path名/string。
您可以上传文件并将其url保存在数据库表中,如下所示:
视图:
@using(Html.BeginForm("Create","Assignment",FormMethod.Post,new {enctype="multipart/form-data"})) { ... <div class="editor-field"> <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%> <%: Html.ValidationMessageFor(model => model.FileLocation) %> </div> ... }
行动:
[HttpPost] public ActionResult Create(Assignment assignment) { if (ModelState.IsValid) { if(Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); assignment.FileLocation = Path.Combine( Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(assignment.FileLocation); } db.Assignments.Add(assignment); db.SaveChanges(); return RedirectToAction("Index"); } } return View(assignment); }
细节:
为了更好的理解,请参阅这篇好文章使用ASP.NET MVC上传文件(或文件)