In this article I will explain with an example, how to display Image after upload using FileUpload in ASP.Net MVC Razor.
The Image will be uploaded using FileUpload element and inside the Controller, the Image will be saved into a Folder (Directory) while the URL of the Image will be assigned to a ViewBag object which will be later used for displaying the Image inside the Image element in View in ASP.Net MVC Razor.
Namespaces
You will need to import the following namespace.
Controller
The Action method Index by default supports the GET operation and hence another overridden method for POST operation is created which accepts the parameter of type HttpPostedFileBase.
Note: The name of the HttpPostedFileBase parameter and the name of FileUpload element must be exact same, otherwise the HttpPostedFileBase parameter will be NULL.
First a check is performed whether Directory (Folder) exists if not then the Directory (Folder) is created and then the Image file is saved to the Directory (Folder).
Finally, the URL of the Image file is assigned to a ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
if (postedFile != null)
{
string fileName = Path.GetFileName(postedFile.FileName);
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
postedFile.SaveAs(path + fileName);
ViewBag.ImageUrl = "Uploads/" + fileName;
}
return View();
}
}
View
The following View consists of an HTML FileUpload element, a Submit Button and an Image element for displaying the uploaded Image file enclosed in a Form element.
The HTML Form has been created using the Html.BeginForm method which accepts the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
The value of the ViewBag object is checked for NULL and if not NULL, then the value is assigned to the SRC attribute of the Image element.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
img
{
height: 150px;
width: 150px;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<span>Select File:</span>
<input type="file" name="postedFile"/>
<hr/>
<input type="submit" value="Upload"/>
<br/>
<br/>
if (ViewBag.ImageUrl != null)
{
<img alt="Uploaded Image" src="@ViewBag.ImageUrl"/>
}
}
</body>
</html>
Screenshot
Downloads