- How to Upload a single File into a folder in ASP.NET MVC5?
- Simple File Uploading Example
Most of the time while developing a project you may required to make a panel that allows users to upload file on the server. There are various aspects of uploading a file on to the server like filtering the file, checking the file types and size, save information into the database etc. You will learn all these things in the different article. Here, I am just focusing only on how can you upload a file in a folder with just very simple example.
Index.cshtml
View Page. Go to Solution Explorer > Views > Home > Index.cshtml
and write the following code.@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>Simple File Upload ASP.NET MVC</h1> </div> <div class="row"> <div class="col-md-4"> @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="files" /> <input type="submit" value="OK" /> } </div> </div>
HomeController.cs
and write following code.using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace SimpleFileUpload.Controllers { public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(); } //Single File Upload [HttpPost] public ActionResult Index(HttpPostedFileBase files) { // Verify that the user selected a file if (files != null && files.ContentLength > 0) { // extract only the filename var fileName = Path.GetFileName(files.FileName); // store the file inside ~/App_Data/uploads folder var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); files.SaveAs(path); } // redirect back to the index action to show the form once again return RedirectToAction("Index"); } } }
Press CTRL + SHIFT + B to build the project and then Press CTRL + F5 to run the project.
OutputSummary
In this programming example, I have explained how can you simply upload a file in a folder using ASP.NET MVC project. This article tells you about single file uploading but in the next article, you will learn how to upload multiple files in ASP.NET MVC with simple programming example.