0

I'm saving uploaded images to my database by using HttpPostedFileBase as follows:

private void Upload(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {
        // save the file to hard drive, we can delete it later
        var FileName = Path.GetFileName(file.FileName);
        var FilePath = Path.Combine(Server.MapPath("~/Content/Images/Uploads/"), FileName);
        file.SaveAs(FilePath);

        byte[] FileBytes;
        using (var Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            using (var Reader = new BinaryReader(Fs))
            {
                FileBytes = Reader.ReadBytes((int)Fs.Length);
            }
        }

        OrtundEntities db = new OrtundEntities();
        ImageModel Image = new ImageModel
        {
            Data = FileBytes,
        };
        db.Images.Add(Image);
        db.SaveChanges();

        //System.IO.File.Delete(filePath);
    }
}

So now I have the file bytes saved in my database.

Clearly I can't use an HTML <img tag to display the image so what delivery mechanism should I use here? Should I rather keep the file and store the filepath along with (or in place of) the byte array?

Ortund
  • 8,095
  • 18
  • 71
  • 139
  • This has already been asked, you can see the answer here: http://stackoverflow.com/questions/17952514/mvc-how-to-display-a-byte-array-image-from-model – Steve K Sep 29 '16 at 21:19

1 Answers1

0

You can do the following

  1. Convert the byte[] to Base64 string, here a sample how to convert
  2. use object tag or img to display the image

Your code should look like:

var base64 = Convert.ToBase64String(bytes); // bytes is the binary  data converted to byte array

then in your view

<img alt="" src='@(string.Format("data:image/jpeg;base64,{0}",Model.Base64))'/>

or

<object data='@(string.Format("data:image/png;base64,{0}",Model.Base64))'></object>

Hope this will help you

Monah
  • 6,714
  • 6
  • 22
  • 52