Upload and display image in MVC application

Upload and display an image in the ASP.NET MVC application.

Here are the steps needed to store an image in a database from an MVC application.

Step 1. First, we create a class in the model folder.

    public class ContentViewModel  
    {  
        public int ID { get; set; }  
        public string Title { get; set; }  
        public string Description { get; set; }  
        [AllowHtml]  
        public string Contents { get; set; }  
        public byte[] Image { get; set; }  
    }

Step 2. Create an Action Method in the Controller class.

    public ActionResult Create()  
    {  
         return View();  
    }

Step 3. Create a View.

    @using (Html.BeginForm("Create","Content", FormMethod.Post, new { enctype ="multipart/form-data" }))  
    {   
       <input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />  
    }  

Step 4. Submit the form.

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

Step 5. Convert Image and Upload code.

    private readonly DBContext db = new DBContext();  
    public int UploadImageInDataBase(HttpPostedFileBase file, ContentViewModel contentViewModel)  
    {  
        contentViewModel.Image = ConvertToBytes(file);  
        var Content = new Content  
        {  
           Title = contentViewModel.Title,  
           Description = contentViewModel.Description,  
           Contents = contentViewModel.Contents,  
           Image = contentViewModel.Image  
        };  
        db.Contents.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;  
    } 

Step 6. Display an image from the database on view. Here we display the content and image from the database.

    public ActionResult Index()  
    {  
        var content = db.Contents.Select(s => new  
        {  
            s.ID,  
            s.Title,  
            s.Image,  
            s.Contents,  
            s.Description  
          });  
          List<ContentViewModel> contentModel = content.Select(item => new ContentViewModel()  
          {  
                ID = item.ID,  
                Title = item.Title,  
                Image = item.Image,  
                Description = item.Description,  
                Contents = item.Contents  
            }).ToList();  
           return View(contentModel);  
    }  

Step 7. Set the Retrieve Image action with the ID.

    <td>  
         <img src="/Content/RetrieveImage/@item.ID" alt="" height=100 width=200 />  
    </td>  
    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.Contents where temp.ID == Id select temp.Image;  
        byte[] cover = q.First();  
        return cover;  
    }  

Insert Image

Display Image

How to use CKEditor in MVC

If you want to use CKEditor in ASP.NET MVC, then check the official CKEditor.NET Control. Download it from CKEditor and unzip this folder. After you download the installation package, copy the ckeditor folder and paste it into our solution.

Step 1. Set a reference for ckeditor.js and jquery.js in the view.

    <script src="~/ckeditor/ckeditor.js"></script>  
    <script src="~/ckeditor/adapters/jquery.js"></script>  

Step 2. Add this code.

    @Html.TextAreaFor(model => model.Contents, new { @class = "ckeditor", placeholder = "Content" })   

Step 3. Allow an HTML attribute in your model like this.

    [AllowHtml]  
    [Required]  
    public string Contents { get; set; }  

Suppose you are not AllowHtml attribute run time exception. A potentially dangerous Request.Form value was detected from the client (Contents="<p>Content Here</p>").

Summary

This code demonstrated how to upload an image to a database in an ASP.NET MVC app.


Similar Articles