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)
- {
-
- 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:
-
Now execute the application.
Select the image and click on the "ShowImage" button.