Monday, 21 September 2015

how to upload image to database and display into page in asp.net MVC4 ?

how to upload image to database and display into page in asp.net MVC4 ? In this post, I am explain how to Upload and retrive image from... thumbnail 1 summary

how to upload image to database and display into page in asp.net MVC4 ?

In this post, I am explain how to Upload and retrive image from database in asp.net Mvc4 application.

Step :- 1 New project

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > click OK

Below Show image
After that new project Create Now, go to the step-2

Step :- 2 Create New Database
Go to  the start menu > click to sql server management > click to connect > now right click to database > select new database > now open popup box > Enter database name and store location for your drive > click on button > Now create database look like this


Step :- 3 Now Create new database table.
click to database name > Right click to table > click to new table > Now enter database table fields > after that save table.
For example

Set primary key for imageId with use for uniqueidentifire datatype then select Rowguid yes.

Otherwise if you can use Imageid datatype for int then select Identity Specification Yes.


Step :- 4 Now go to the visual studio and Create Entity data model
Go to Solution Explorer > Right Click on Project name  > Add > New item >Select Data > Select ADO.net Entity Data Model > Enter model name > Click Add Button.
Below Show Image.




Now,
A popup window will Open (Entity Data Model Wizard) > Select Generate from database > Next >



Chose your data connection > select your database > next >Select Entity framework > next 
Below Show image



 Select tables > enter Model Namespace > Finish.  

Finally Entity data model was Created

Step :- 5 Create a controller
Go to solution explore > Right click on controller folder > Add > controller

Now Enter Controller name > select Empty MVC controller > Add


Step :- 6 Add action into your controller for get method for upload image to the database

Here i have added "Upload" action method into "Uploadcontroller". Write this following code

       [HttpGet]
        public ActionResult Upload()
        {
            return View();
        } 

Step :- 7 Add a view for Upload image
Here Right Click On Upload Action method > Click Add View (Now popup will be open) > Enter View name > select view engine (Razor) > Checkbox select for "Create strong-type view" > select your model calss >Click to Add button


@model UploadImageDemo.Models.UploadImage

@{
    ViewBag.Title = "Upload";
}

<h2>Upload</h2>

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>UploadImage</legend>

    
        <div class="editor-field">
            @Html.HiddenFor(model => model.ImageId)
       </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ImageName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ImageName)
            @Html.ValidationMessageFor(model => model.ImageName)
        </div>

        <div class="editor-label">
            <label>product Image</label>
        </div>
        <div class="editor-field">
            <input id="ImageUpload" type="file" name="ImageUpload" />
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Step :-8 Add new action into your controller for Post method for upload image to the database

Here i have added "Upload" action with model parameter "uploadimage" into UploadController. pls write this code. 

[HttpPost]
        public ActionResult Upload(UploadImage uploadimage)
        {
            HttpPostedFileBase file = Request.Files["ImageUpload"];

            uploadimage.ImageId = Guid.NewGuid();

            if (file != null && file.FileName != null && file.FileName != "")
            {
                FileInfo fi = new FileInfo(file.FileName);
                if (fi.Extension != ".jpeg" && fi.Extension != ".jpg")
                {
                    TempData["Errormsg"] = "Image File Extension is Not valid";
                    return View(uploadimage);
                }
                else
                {
                    string image1 = "image1";
                    uploadimage.UploadImage1 = uploadimage.ImageId + fi.Extension;
                   
                    file.SaveAs(Server.MapPath("~/Content/Image/" + uploadimage.ImageId + fi.Extension));

                }
            }
            using (abcEntities db = new abcEntities())
            {
                db.UploadImages.Add(uploadimage);
                db.SaveChanges();
                return RedirectToAction("Gallery");
            }


            return View(uploadimage);
        }


Step-9: Add new action into your controller for fetch images from database and show in view.

Now  I have added "Gallery" Action into "Upload" Controller. Please write this following code

public ActionResult Gallery()
        {
            using (abcEntities db = new abcEntities())
            {
                var image = db.UploadImages.ToList();
                return View(image);
            }
          
        } 

Step:-10: Add view for Gallery Action.

Here Right Click On Gallery Action method > Click Add View (Now popup will be open) > Enter View name > select view engine (Razor) > Checkbox select for "Create strong-type view" > select your model calss >Click to Add button 

Please write this following code

@model IEnumerable<UploadImageDemo.Models.UploadImage>

@{
    ViewBag.Title = "Gallery";
}

<h2>Image Gallery</h2>

<table>
    <tr>
       
        <th>
            @Html.DisplayNameFor(model => model.ImageName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.UploadImage1)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
       
        <td>
            @Html.DisplayFor(modelItem => item.ImageName)
        </td>
        <td>
            <img src="@Url.Content("~/Content/Image/")@item.UploadImage1" width="100" height="100" />
        </td>
      
    </tr>
}

</table>

 

Step :- 11 Run Application

Output will be given below

 

Thnx for watching tutorial......

 

7 comments

  1. Very well explained how to upload image using MVC and display.

    ReplyDelete
  2. hello I have many more error when I wrtite this prject. Please send me anyone to project. tuncayyturan@gmail.com

    ReplyDelete
  3. Thanks but it is overwriting previous uploaded images when using Imageid datatype for int

    ReplyDelete
  4. Sorry I got it right, I used "Guid.NewGuid().GetHashCode();" instead of "Guid.NewGuid();" now is working fine. Thank you.

    ReplyDelete