I have stored the image in a column of a table alongside with other information , but i have troble displaying the image when retrieving the whole information about the post. I am getting 'broken img' icon.
Model:
public class Event
{
[Key]
public int Id { get; set; }
public string EventName { get; set; }
public byte[] EventPhoto { get; set; }
}
Create Action:
[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);
}
Input view:
@Html.LabelFor(m => m.EventPhoto)
<input type="file" name="Event" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
Display Action:
public ActionResult DisplayImg(Event events)
{
var bdEvents = HttpContext.GetOwinContext().Get<EventSpotDbContext>();
var userImage = bdEvents.Users.Where(x => x.Id == (events.Id).ToString()).FirstOrDefault();
return new FileContentResult(events.EventPhoto, "image/jpg");
}
Display View:
<div class="container">
<article>
<p> @Model.EventName </p>
<img src="@Url.Action("DisplayImg", "Event" )" />
</article>
Any solution to my problem?
@Url.Action("DisplayImg", "Event" )does not pass any data to theDisplayImg()method and yourEvent eventsparemeter is just a default instance - the value ofEventPhotoisnull! But that method should never contain a parameter which is a model anyway - its needs to be (say)int IDwhereIDis the identifier of theEvent, and you get theEventfrom the database. (and if you did try to pass the properties ofEventto that method, it would certainly throw an exception because of the query string limit)@Url.Action("DisplayImg, new { id = Model.Id })