我有一个 ActionResult 将数据绑定到模型并将其添加到数据库中。现在我想要的是有一个文件上传器和 ActionResult 来存储文件并将它们的 FileName 添加到数据库中(这样我可以稍后显示文件/图像)。最好的方法是什么?这是我到目前为止得到的(它可以存储文件,但我不确定 EF 有多智能,以及数据类型有多复杂):
模型类:
public class Annonce
{
public int Id { get; set; }
public string Company { get; set; }
public string Size { get; set; }
public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
}
视图(使用 mircosoft.web.helpers):
@using (Html.BeginForm("Create", "Annonce", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Annonce</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Company)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Company)
@Html.ValidationMessageFor(model => model.Company)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Size)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Size)
@Html.ValidationMessageFor(model => model.Size)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FileUpload)
</div>
<div class="editor-field">
@FileUpload.GetHtml(uploadText: "Opret")
</div>
</fieldset>
控制器:
[HttpPost]
public ActionResult Create(Annonce annonce)
{
if (ModelState.IsValid)
{
//System.IO stuff
foreach (var file in annonce.FileUpload)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
//Database stuff
db.Annoncer.Add(annonce);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(annonce);
}
这可以很好地存储文件。现在我想要的file.FileName
是存储在数据库中。起初,我虽然 EF 只是将文件或文件名绑定model.FileUpload
到数据库。但我猜数据类型太复杂了?所以我想制作一个list<HttpPostedFileBase>
并在file.FileName
那里添加?或者可能创建一个全新的实体/表,其中所有文件名都存储为带有引用 ID 的字符串?有什么建议么?