Upload images to database in MVC3 Razor


  1. In this article we will see how to store images to the database.
  2. We have used VarBinary(MAX) datatype in SQL Server database. We are converting the image into its bytes and storing in the database.
  3. While rendering back on UI, we can again convert it into image from bytes and render.
Demo

Database :



In the above image, ImageBytes is the column which stores the image bytes. We have used VarBinary(Max) datatype.

Code:

The following code describes how we have used upload control and saved image file in the database.

View:


<div>
        @using(Html.BeginForm("UploadImage","LoginRegister", FormMethod.Post, new { @enctype = "multipart/form-data" }))
        {
            @Html.Hidden("AlbumName",Model.AlbumName)
   <span id="UploadStatus" style="font-family:comic sans ms;color:white;margin-left:40px;"></span><br/>
            <input style="margin-left:40px;cursor:pointer;" type="file" name="file" id="file"/>
            <input type="submit" style="margin-left:40px;cursor:pointer;" id="upload" value="Upload"/>
        }
    </div>

We have used BeginForm helper to post the file or form to the controller method. On submit the form data will be posted to UploadImage method in LoginRegister controller.

Controller :



[HttpPost]
        public ActionResult UploadImage(ImageViewModel imageViewModel)
        {
            if (ModelState.IsValid)
            {
                Gallary gallary = new Gallary();
                gallary.SavePlayerImage(imageViewModel, Convert.ToInt32(Session["UserId"]),
                                        Convert.ToInt32(Session["AlbumId"]));
                return RedirectToAction("GetImages", new { album = imageViewModel.AlbumName.ToString() });
            }
            else
            {
                TempData["InvalidImage"] = "Upload images only";
                return RedirectToAction("GetImages", new { album = imageViewModel.AlbumName.ToString() });
            }
        }

The action method receives an object of ImageViewModel which is our view model. We are then using the view model object to save our image.

ViewModel :



public class ImageViewModel
    {
        public List ImageList { get; set; }

        public string AlbumName { get; set; }

        public string FileExtension { get; set; }

        [ImageValidator]
        public HttpPostedFileBase File { get; set; }
    }

The above is our view model. We have used HttpPostedFileBase class to get our image. The File property contains the image on post, we can then save this image in database.

Service :

In the service class we have two methods as shown below :



    public void SavePlayerImage(ImageViewModel model,int userId,int albumId)
        {
            byte[] imageBytes = ConvertToBytes(model.File);
            Images playerImage = new Images();
            playerImage.AlbumId = albumId;
            playerImage.UserId = userId;
            playerImage.ImageBytes = imageBytes;
            playerImage.Extension = model.File.ContentType;
            GallaryDataContext gallaryDataContext = new GallaryDataContext();
            gallaryDataContext.Images.InsertOnSubmit(playerImage);
            gallaryDataContext.SubmitChanges();
        }

The above method calls ConvertToBytes method to convert image to bytes. Finally the image details are saved. The method to convert it into bytes is shown below.



    public byte[] ConvertToBytes(HttpPostedFileBase Image)
        {
            byte[] imageBytes = null;
            BinaryReader reader = new BinaryReader(Image.InputStream);
            imageBytes = reader.ReadBytes((int)Image.ContentLength);
            return imageBytes;
        }

The above method converts the image file into its bytes and returns the byte array. This byte array is then stored in the database.

Screenshot :





Thus following the above steps we can store image in the database.


You may also like to read:


Upload multiple files to database

4 comments:

  1. buenos dias he intentado realizar la labor de ingreg¿sar imagenes en mi site en sql server 2008, pero simepre me hacen falta usings o referencias de servicio

    no se si ud me pueda ayudar


    Saludos mi nombre es Jeisson Rozo

    jeisonrozo@gmail.com


    Colombia

    ReplyDelete
  2. Buenas tardes he intnetentado vario metodos para ingregsar imagenes a sql server como ud lo explica pero siempre me falta alguna referencia

    no se si pueda ayudarme

    Saludos

    Jeisson Rozo

    ReplyDelete
  3. Dear Sir/Madam,

    Can you send me with the source code,
    of this project
    Siqichen970@hotmail.com

    Thank you

    Siqi

    ReplyDelete
  4. hi
    can u please send me the source code for image upload.
    thank you
    p_sebestyen@hotmail.com

    ReplyDelete