如何将 2 个图像文件上传到 MVC C# 5 数据库中各自的 Byte[] 数组 属性?
How to Upload 2 Image Files into MVC C# 5 database in its respective Byte[] array property?
public class Opportunity
{
[Key]
public int OpportunityId { get; set; }
[Required(ErrorMessage = "Graphics Image is required")]
public byte[] Graphics { get; set; }
[DisplayName("Faculty Picture")]
[Required(ErrorMessage = "Faculty Image is required")]
public byte[] FacultyPicture { get; set; }
}
控制器:
namespace Kaust.Views.Opportunities
{
public class OpportunitiesController : Controller
{
private KaustContext db = new KaustContext();
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OpportunityId,Graphics,FacultyPicturen")] Opportunity opportunity)
{
if (ModelState.IsValid)
{
db.Opportunities.Add(opportunity);
db.SaveChanges();
return RedirectToAction("Index");
}
}
查看:
创建索引:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Opportunity</h4>
<hr />
@Html.Images(m => m.Graphics, "Graphics", "id")
@Html.ValidationMessageFor(model => model.Graphics, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-horizontal">
<h4>Opportunity</h4>
<hr />
@Html.Images(m => m.FacultyPicture, "Graphics", "id")
@Html.ValidationMessageFor(model => model.FacultyPicture, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
并且@Html.Images 是一个定制助手:
public static IHtmlString Images<TModel,TValue>(this HtmlHelper<TModel> helper,System.Linq.Expressions.Expression<Func<TModel, TValue>> expression, string name, string id){
TagBuilder tb = new TagBuilder("input");
tb.Attributes.Add("ex", expression.ToString());
tb.Attributes.Add("name", name);
tb.Attributes.Add("id", id);
tb.Attributes.Add("type", "file");
tb.Attributes.Add("accept", "Image/*");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
它创建了这个输出:
<input accept="Image/*" ex="m => m.Graphics" id="id" name="Graphics" type="file">
当我点击提交按钮时:
输入的 Base-64 字符串无效,因为它包含非 Base-64 字符、两个以上的填充字符或填充字符中的非法字符。
我已经看到了几种将图像文件更改为 Byte[] 的方法,但我不知道如何在提交按钮之前执行此操作,或者因为它没有进入 "httppost method"。
我试过这个解决方案。但是......我仍然得到错误。
How to upload/display images using ASP.net MVC4 with Entity Framework
http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files
问题是单击提交按钮后如何将这些文件保存到数据库中?
模型中的属性需要 HttpPostedFileBase
(而不是 byte[]
)才能绑定到视图中的文件输入。由于您还想将文件存储在数据库中,因此您将需要一个单独的视图模型和数据模型
// View model (Note ID property not required)
public class OpportunityVM
{
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase Graphics { get; set; }
[DisplayName("Faculty Picture")]
public HttpPostedFileBase FacultyPicture { get; set; }
}
并且在POST方法中
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([OpportunityVM model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// Initialize data model
Opportunity opportunity = new Opportunity();
using (var reader = new System.IO.BinaryReader(model.Graphics.InputStream))
{
opportunity.Graphics = reader.ReadBytes(model.Graphics.ContentLength);
}
if (model.FacultyPicture != null && modelFacultyPicture.ContentLength > 0)
{
// ditto for FacultyPicture
}
db.Opportunities.Add(opportunity);
db.SaveChanges();
return RedirectToAction("Index");
}
请注意,您还需要在表单标签中包含 enctype = "multipart/form-data"
属性
@using (Html.BeginForm("Create", "Opportunities", FormMethod.Post, new { enctype = "multipart/form-data" }))
旁注:您的生成无效 html。模型中的两个文件输入都有 id="id"
(重复的 id
属性)
无需将 name
和 id
传递给助手(事实上,传递 name
的小拼写错误意味着绑定将失败)。而是使用 ModelMetadata
来生成正确的属性。此外,ex
不是一个有效的属性,它不清楚你试图用 tb.Attributes.Add("ex", expression.ToString());
实现什么,但它应该被删除。
public static IHtmlString Images<TModel,TValue>(this HtmlHelper<TModel> helper,System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)
{
string name = ExpressionHelper.GetExpressionText(expression);
string id = HtmlHelper.GenerateIdFromName(name);
TagBuilder tb = new TagBuilder("input");
// tb.Attributes.Add("ex", expression.ToString());
tb.MergeAttribute("name", name);
tb.MergeAttribute("id", id);
tb.MergeAttribute("type", "file");
tb.MergeAttribute("accept", "Image/*");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
public class Opportunity
{
[Key]
public int OpportunityId { get; set; }
[Required(ErrorMessage = "Graphics Image is required")]
public byte[] Graphics { get; set; }
[DisplayName("Faculty Picture")]
[Required(ErrorMessage = "Faculty Image is required")]
public byte[] FacultyPicture { get; set; }
}
控制器:
namespace Kaust.Views.Opportunities
{
public class OpportunitiesController : Controller
{
private KaustContext db = new KaustContext();
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OpportunityId,Graphics,FacultyPicturen")] Opportunity opportunity)
{
if (ModelState.IsValid)
{
db.Opportunities.Add(opportunity);
db.SaveChanges();
return RedirectToAction("Index");
}
}
查看:
创建索引:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Opportunity</h4>
<hr />
@Html.Images(m => m.Graphics, "Graphics", "id")
@Html.ValidationMessageFor(model => model.Graphics, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-horizontal">
<h4>Opportunity</h4>
<hr />
@Html.Images(m => m.FacultyPicture, "Graphics", "id")
@Html.ValidationMessageFor(model => model.FacultyPicture, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
并且@Html.Images 是一个定制助手:
public static IHtmlString Images<TModel,TValue>(this HtmlHelper<TModel> helper,System.Linq.Expressions.Expression<Func<TModel, TValue>> expression, string name, string id){
TagBuilder tb = new TagBuilder("input");
tb.Attributes.Add("ex", expression.ToString());
tb.Attributes.Add("name", name);
tb.Attributes.Add("id", id);
tb.Attributes.Add("type", "file");
tb.Attributes.Add("accept", "Image/*");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
它创建了这个输出:
<input accept="Image/*" ex="m => m.Graphics" id="id" name="Graphics" type="file">
当我点击提交按钮时:
输入的 Base-64 字符串无效,因为它包含非 Base-64 字符、两个以上的填充字符或填充字符中的非法字符。
我已经看到了几种将图像文件更改为 Byte[] 的方法,但我不知道如何在提交按钮之前执行此操作,或者因为它没有进入 "httppost method"。
我试过这个解决方案。但是......我仍然得到错误。
How to upload/display images using ASP.net MVC4 with Entity Framework
http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files
问题是单击提交按钮后如何将这些文件保存到数据库中?
模型中的属性需要 HttpPostedFileBase
(而不是 byte[]
)才能绑定到视图中的文件输入。由于您还想将文件存储在数据库中,因此您将需要一个单独的视图模型和数据模型
// View model (Note ID property not required)
public class OpportunityVM
{
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase Graphics { get; set; }
[DisplayName("Faculty Picture")]
public HttpPostedFileBase FacultyPicture { get; set; }
}
并且在POST方法中
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([OpportunityVM model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// Initialize data model
Opportunity opportunity = new Opportunity();
using (var reader = new System.IO.BinaryReader(model.Graphics.InputStream))
{
opportunity.Graphics = reader.ReadBytes(model.Graphics.ContentLength);
}
if (model.FacultyPicture != null && modelFacultyPicture.ContentLength > 0)
{
// ditto for FacultyPicture
}
db.Opportunities.Add(opportunity);
db.SaveChanges();
return RedirectToAction("Index");
}
请注意,您还需要在表单标签中包含 enctype = "multipart/form-data"
属性
@using (Html.BeginForm("Create", "Opportunities", FormMethod.Post, new { enctype = "multipart/form-data" }))
旁注:您的生成无效 html。模型中的两个文件输入都有 id="id"
(重复的 id
属性)
无需将 name
和 id
传递给助手(事实上,传递 name
的小拼写错误意味着绑定将失败)。而是使用 ModelMetadata
来生成正确的属性。此外,ex
不是一个有效的属性,它不清楚你试图用 tb.Attributes.Add("ex", expression.ToString());
实现什么,但它应该被删除。
public static IHtmlString Images<TModel,TValue>(this HtmlHelper<TModel> helper,System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)
{
string name = ExpressionHelper.GetExpressionText(expression);
string id = HtmlHelper.GenerateIdFromName(name);
TagBuilder tb = new TagBuilder("input");
// tb.Attributes.Add("ex", expression.ToString());
tb.MergeAttribute("name", name);
tb.MergeAttribute("id", id);
tb.MergeAttribute("type", "file");
tb.MergeAttribute("accept", "Image/*");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}