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.
- 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.
- From the "MVC4 Project" window select "Web API".
- Click on the "OK" button.
- Now select the "HomeController"
- In the "Solution Explorer".
- Expand the Controller folder.
- Select the "HomeController".
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();
}
}
}
- Now write the HTMl code in the "index.cshtml" file:
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" />
<input type="submit" value="ShowImage" name="Command" /><br />
<img src="@ViewBag.ImagPath" style="width:200px; height:200px;"/>
</div>
<div>
</div>
}
-
Now execute the application.
Select the image and click on the "ShowImage" button.