httppostedfilebase

Save httppostedfilebase as image in SQL


I have a situation where I am getting an image as httppostedfilebase type in my MVC code. I have a corresponding Image type column in my SQL db.

I need to know how do I convert/Save this httppostedfilebase type as image in my DB.


Solution

  • Create a function to convert HttpPostedFileBase object to file

    public byte[] ConvertToByte(HttpPostedFileBase file)
        {
            byte[] imageByte = null;
            BinaryReader rdr = new BinaryReader(file.InputStream);
            imageByte = rdr.ReadBytes((int)file.ContentLength);
            return imageByte;
        }
    

    Code like this in Your Controller

    public ActionResult Create(AdminDetailsViewModel viewmodel)
        {
            if (ModelState.IsValid)
            {
            HttpPostedFileBase file = Request.Files["ImageData"];
            viewmodel.Image = ConvertToByte(file);
            db.YourDbContextSet.Add(viewmodel);
            db.SaveChanges();
            }
        }
    

    Hope this will help