- Mudita Rathore
- Feb 16, 2021
- 65.9k
- 0
- 1
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".
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.IO;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.Mvc;
- namespaceMvcApplication3.Controllers
- {
- publicclassHomeController:Controller
- {
- publicActionResultIndex()
- {
- returnView();
- }
- [HttpPost]
- publicActionResultIndex(HttpPostedFileBasefile)
- {
- //extractonlythefielname
- varimageName=Path.GetFileName(file.FileName);
- varimgsrc=Path.Combine(Server.MapPath("~/images/"),imageName);
- stringfilepathToSave="images/"+imageName;
- file.SaveAs(imgsrc);
- ViewBag.ImagPath=filepathToSave;
- returnView();
- }
- }
- }
Add the following code:
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="Uploadthefileanddisplaytheuploadedimage";
- }
- @using(Html.BeginForm("Index","Home",FormMethod.Post,new{enctype="multipart/form-data"}))
- {
- <div>
- SelectImage
- <inputtype="file"name="file"/>
- <inputtype="submit"value="ShowImage"name="Command"/><br/>
- <imgsrc="@ViewBag.ImagPath"style="width:200px;height:200px;"/>
- </div>
- <div>
- </div>
- }
Now execute the application.
Select the image and click on the "ShowImage" button.