I have a form that has input fields and file upload field, I think that I have done everything but I have a problem with the binary reader. Model:
public class Event
{
[Key]
public int Id { get; set; }
public string EventName { get; set; }
public byte[] EventPhoto { get; set; }
}
Controller:
[Authorize]
[HttpPost]
public ActionResult Create(Event events, [Bind(Exclude = "EventPhoto")]EventController model)
{
if (ModelState.IsValid)
{
using (var database = new EventSpotDbContext())
{
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase poImgFile = Request.Files["EventPhoto"];
using (var binary = new BinaryReader(poImgFile.InputStream))
{
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
events.EventPhoto = imageData;
database.Events.Add(events);
database.SaveChanges();
return RedirectToAction("Main");
}
}
return View(events);
}
View:
@using (Html.BeginForm("Create", "Event", FormMethod.Post, new { @class = "form-horizontal" , role = "form", enctype = "multipart/form-data" } ))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary("", new { @class = "text-danger" })
@Html.LabelFor(m => m.EventName)
@Html.TextBoxFor(m => m.EventName)
@Html.LabelFor(m => m.EventPhoto)
<input type="file" name="Event" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
<input type="submit" value="Create" class="btn btn-success" />
}
On post Error:
Server Error in '/' Application.
Object reference not set to an instance of an object. NullReferenceException: Object reference not set to an instance of an object.
Line 83: using (var binary = new >BinaryReader(poImgFile.InputStream))