I have been through pretty much every post on this site it seems that deals with image upload & persistence to a sql server database however, something I'm doing is still not right.
The image is either not saving correctly or pulling from the database correctly as while bytes are being written / retrieved the image is not valid. When comparing the size of the image that was uploaded to the original the size is different (larger)?
Model:
public byte[] Photo { get; set; }
public string PhotoMimeType { get; set; }
public string PhotoName { get; set; }
Sql Server:
[PhotoMimeType] [nvarchar](50) NULL,
[PhotoName] [nvarchar](50) NULL,
[Photo] [image] NULL,
Within a controller I have the following to save an image:
public ActionResult Edit(AgentInfo modifiedAgent, HttpPostedFileBase postedFile)
{
if(ModelState.IsValid)
{
var model = _agentRepository.GetByID(modifiedAgent.AgentID);
if (TryUpdateModel(model))
{
if (postedFile != null)
{
int imageLength = postedFile.ContentLength;
byte[] imgBytes = new byte[imageLength];
postedFile.InputStream.Read(imgBytes, 0, imageLength);
model.PhotoMimeType = postedFile.ContentType;
model.PhotoName = postedFile.FileName;
model.Photo = imgBytes;
}
_agentRepository.Save(model);
return RedirectToAction("ManageAgents", "Agent");
}
}
return View("Edit", modifiedAgent);
}
The retrieval:
[HttpGet]
public ActionResult GetImage(int id)
{
var agent = _agentRepository.GetByID(id);
return File(agent.Photo, agent.PhotoMimeType, agent.PhotoName);
}
The display:
<img src='@Url.Action("GetImage", "Agent", new { id = Model.AgentID })' />
EDIT:
Well after thinking it was a problem with how I was wiring this all together it turned out to be my database mappings.....frick
Fyi, when mapping with fluent-nhibernate and you want to save image bytes, sql data type is varbinary(max) with the following mapping:
Map(x => x.Photo).Column("Photo").Length(2147483647).CustomSqlType("varbinary(MAX)");