型号
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; }
}}
Controller
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>
如果我想将文件存储到服务器/路径文件夹中,而在数据库中我只想存储路径名称/字符串,我该如何存储文件。
最佳答案
您可以像这样上传文件并将其 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);
}
详情:
为了更好地理解,请参阅 this good article Uploading a File (Or Files) With ASP.NET MVC
关于c# - ASP.NET MVC 4 C# HttpPostedFileBase,如何存储文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125127/