2

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)");

1 Answer 1

4

Try rewinding the InputStream just before reading it:

postedFile.InputStream.Position = 0;

or use a temporary MemoryStream:

using (var memoryStream = new MemoryStream())
{
    postedFile.InputStream.CopyTo(memoryStream);
    model.Photo = memoryStream.ToArray();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Darin after going through both options you provided it lead me to deeper digging and I found the problem which was in my fluent-nhibernate mappings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.