In this article I will explain with an example, how to fetch File from Form Collection in ASP.Net Core MVC.
The uploaded Files are available in the Request.Form.Files collection in ASP.Net Core MVC.
You will need to import the following namespaces.
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method handles the operation of uploading of File.
The File is fetched from the Request.Form.Files collection using the name of the HTML FileUpload element.
Then a check is performed whether Directory (Folder) exists if not then the Directory (Folder) is created inside the www Folder using IHostingEnvironment interface and then the file is saved to the Directory (Folder) using the FileStream class.
Finally, a message is displayed to the user using TempData and a redirection is done to the Index Action method.
public class HomeController : Controller
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
Environment = _environment;
public IActionResult Index()
public IActionResult Upload()
if (Request.Form.Files.Count > 0)
IFormFile postedFile = Request.Form.Files["postedFile"];
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
string fileName = Path.GetFileName(postedFile.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
TempData["Message"] = "File uploaded successfully.";
The View consists of an HTML Form which has been created using the Razor Tag attributes with the following attributes.
asp-action – Name of the Action. In this case the name is Upload.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
There is an HTML FileUpload element, a Submit Button and a SPAN element for displaying Message enclosed in the Form element.
The HTML Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation.
Layout = null;
<meta name="viewport" content="width=device-width" />
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Upload">
<input type="file" name="postedFile" />
<input type="submit" value="Upload" />