1

I am trying to upload and retrieve image from SQL server database. I created model, Controller and view as below.

Viewmodel is very similiar to actual modal

CheckoutModel.cs

public class CheckOutViewModel
{
    public int ID { get; set; }
    public ApplicationUser CandidateId { get; set; }
    [Required]
    public byte[] Image { get; set; }
}

Also i created a controller to upload and display images with action methods namely index, create and retreive

Index method is used to display images , create method is used to upload and save image in database and retrieve method is used to query the image according to its id.

CheckOutController.cs

using Microsoft.AspNet.Identity;
using shanuMVCUserRoles.Repositories;
using shanuMVCUserRoles.ViewModels;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace shanuMVCUserRoles.Models
{
    public class CheckOutController : Controller
    {
        private readonly ApplicationDbContext db;
        public CheckOutController()
        {
            db = new ApplicationDbContext();
        }

        [Route("Index")]
        [HttpGet]
        public ActionResult Index()
        {
            var content = db.Checkouts.Select(s => new
            {
                s.ID,
                s.CandidateId,
                s.Image,
            });

            List<CheckOutViewModel> contentModel = content.Select(item => new CheckOutViewModel()
            {
                ID = item.ID,
                CandidateId = item.CandidateId,
                Image = item.Image,
            }).ToList();
            return View(contentModel);
        }


        public ActionResult RetrieveImage(int id)
        {
            byte[] cover = GetImageFromDataBase(id);
            if (cover != null)
            {
                return File(cover, "image/jpg");
            }
            else
            {
                return null;
            }
        }

        public byte[] GetImageFromDataBase(int Id)
        {
            var q = from temp in db.Checkouts where temp.ID == Id select temp.Image;
            byte[] cover = q.First();
            return cover;
        }

        // GET: CheckOut
        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [Route("Create")]
        [HttpPost]
        public ActionResult Create(CheckOutViewModel model)
        {
            HttpPostedFileBase file = Request.Files["ImageData"];
            CheckOutRepository service = new CheckOutRepository();
            int i = service.UploadImageInDataBase(file, model);
            if (i == 1)
            {
                return RedirectToAction("Index");
            }
            return View(model);
        }

    }

}

Then i created a repository folder to save images and fields in database and also a method for converted image to bytes.

CheckoutRepostiory.cs

public class CheckOutRepository
{
    private readonly ApplicationDbContext db;
    public CheckOutRepository()
    {
        db = new ApplicationDbContext();
    }
    public int UploadImageInDataBase(HttpPostedFileBase file, CheckOutViewModel contentViewModel)
    {
        contentViewModel.Image = ConvertToBytes(file);
        var userId = HttpContext.Current.User.Identity.GetUserId();
        var member = db.Users.Single(u => u.Id == userId);
        var Content = new CheckOut
        {
            CandidateId = member,
            Image = contentViewModel.Image
        };
        db.Checkouts.Add(Content);
        int i = db.SaveChanges();
        if (i == 1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    public byte[] ConvertToBytes(HttpPostedFileBase image)
    {
        byte[] imageBytes = null;
        BinaryReader reader = new BinaryReader(image.InputStream);
        imageBytes = reader.ReadBytes((int)image.ContentLength);
        return imageBytes;
    }
}

Also i created the index view and then i placed the image in image tag using the for each loop.

Index.cshtml

@foreach (var item in Model)
{
    <tr>
        <td>
            <img src="/Content/RetrieveImage/@item.ID" alt="" height=100 width=200 />
        </td>
    </tr>
}

2 Answers2

0

I have one alternative solution: Alter your database table to set a field as varchar2 and store your image as string path on it:

Then after you same change, you can do in your MODEL as well as where it is required.

public class CheckOutViewModel
{
    public int ID { get; set; }
    public ApplicationUser CandidateId { get; set; }
    [Required]
    public string Image { get; set; }
}
Unknown_Coder
  • 764
  • 6
  • 24
0

Something like this may work... if you have image bytes in your model object

@foreach (var item in Model)
{
    <tr>
        <td>
         @{
           var base64 = Convert.ToBase64String(item.Image);
           var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
          }
        <img src="@imgSrc" alt="" height=100 width=200 />
        </td>
    </tr>
}

or

<img src="data:image;base64,@System.Convert.ToBase64String(item.Image)" width="200" height="100"/>

hope it helps

Zaheer Ul Hassan
  • 771
  • 9
  • 24