Introduction
This article explains how to upload a file to a server in ASP.NET MVC 4.
Step 1: Create New Project
Go to "File" -> "New" -> "Project..." then select "ASP.NET MVC4 Web Application" then enter Application Name then click "OK" then select "Internet Application" then select "View Engine Razor" then click "OK".
Step 2: Add a new controller
Go to Solution Explorer then right-click on the Controllers folder from Solution Explorer then seelct "Add" > "Controller" then enter the Controller name then select the Templete "Empty MVC Controller".
Step 3: Add new action into your controller for uploading file
Here I added a "file” action for the file uploading. You can access the posted file directly through the HttpPostedFilesBase object due to model binding.
- public ActionResult file()
- {
- return View();
- }
- [HttpPost]
- public ActionResult file(HttpPostedFileBase file)
- {
- if (file != null && file.ContentLength > 0)
- try
- {
- string path = Path.Combine(Server.MapPath("~/Content/files"),
- Path.GetFileName(file.FileName));
- file.SaveAs(path);
- ViewBag.Message = "File uploaded successfully";
- }
- catch (Exception ex)
- {
- ViewBag.Message = "ERROR:" + ex.Message.ToString();
- }
- else
- {
- ViewBag.Message = "You have not specified a file.";
- }
- return View();
- }
Step 4: Add view for the action.
Right-click on the Action Method then select "Add View" then enter the View Name then select "View Engine" then "Add".
Our form method is POST and the form encoding type is "multipart/form-data". These parameters are required for uploading binary data to the server.
- @{
- ViewBag.Title = "file";
- }
-
- <h2>Upload file</h2>
- @using (Html.BeginForm ("file", "upload", FormMethod.Post,
- new { enctype = "multipart/form-data" }))
- {
- <input type="file" name="file" id="file"/><br><br>
- <input type="submit" value="Upload file"/>
- <br><br>
- @ViewBag.Message
- }
Your view will look like:
After uploading the file you can see your file in your project directory location ~/Content/files.