Displaying Upload Image in Image Controller in Web API

Introduction

This article explains how to display the uploading image in the image control. First we browse the file and select the image then we click on the show image button, it displays the uploading image.

Use the following procedure to create a sample of the application.

  1. Create an application:
    • Start Visual Studio 2012.
    • From the Start window select "Installed" -> "Visual C#" -> "Web".
    • Select "ASP.NET MVC4 Web Application" and click on the "Ok" button.

      Select MVC4 Application
    • From the "MVC4 Project" window select "Web API".

      Select Web API

    • Click on the "OK" button.
  2. Now select the "HomeController"
    • In the "Solution Explorer".
    • Expand the Controller folder.
    • Select the "HomeController".
    • Select Controller

      Add the following code:

      1. using System;  
      2. using System.Collections.Generic;  
      3. using System.IO;  
      4. using System.Linq;  
      5. using System.Web;  
      6. using System.Web.Mvc;  
      7. namespace MvcApplication3.Controllers  
      8. {  
      9.     public class HomeController : Controller  
      10.     {  
      11.         public ActionResult Index()  
      12.         {  
      13.             return View();  
      14.         }  
      15.         [HttpPost]  
      16.         public ActionResult Index(HttpPostedFileBase file)  
      17.         {  
      18.             // extract only the fielname            
      19.             var imageName = Path.GetFileName(file.FileName);                     
      20.            var imgsrc = Path.Combine(Server.MapPath("~/images/"), imageName);        
      21.             string filepathToSave = "images/" + imageName;  
      22.             file.SaveAs(imgsrc);  
      23.             ViewBag.ImagPath = filepathToSave;            
      24.             return View();  
      25.         }  
      26.     }  
      27. }  
  3. Now write the HTMl code in the "index.cshtml" file:

    • In the "Solution Explorer".

    • Expand "Views" folder.

    • Select "Home" -> "index.cshtml".

      Add the following code:

      1. @{  
      2.     ViewBag.Title = "Upload the file and display the uploaded image";  
      3. }  
      4. @using (Html.BeginForm("Index""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
      5. {  
      6.     <div>  
      7.         Select Image  
      8.         <input type="file" name="file" />     
      9.         <input type="submit" value="ShowImage" name="Command" /><br />  
      10.         <img src="@ViewBag.ImagPath"  style="width:200px; height:200px;"/>  
      11.     </div>  
      12.     <div>  
      13.     </div>  
      14. }
  4. Now execute the application.

Output

Select the image and click on the "ShowImage" button.

Select image



Display upload image