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.
  1. Now select the "HomeController"
  • In the "Solution Explorer".
  • Expand the Controller folder.
  • Select the "HomeController".

Select Controller

Add the following code:

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MvcApplication3.Controllers

{

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

        [HttpPost]

        public ActionResult Index(HttpPostedFileBase file)

        {

            // extract only the fielname          

            var imageName = Path.GetFileName(file.FileName);                   

           var imgsrc = Path.Combine(Server.MapPath("~/images/"), imageName);      

            string filepathToSave = "images/" + imageName;

            file.SaveAs(imgsrc);

            ViewBag.ImagPath = filepathToSave;          

            return View();

        }

    }

}

  1. 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:

@{

    ViewBag.Title = "Upload the file and display the uploaded image";

}

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

{

    <div>

        Select Image

        <input type="file" name="file" />&nbsp;&nbsp;&nbsp;

        <input type="submit" value="ShowImage" name="Command" /><br />

        <img src="@ViewBag.ImagPath"  style="width:200px; height:200px;"/>

    </div>

    <div>

    </div>

}

  1. Now execute the application.

Output

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

Select image



Display upload image

Up Next
    Ebook Download
    View all
    Learn
    View all