How to Implement File Upload in ASP.NET MVC
By Tan Lee Published on Dec 05, 2024 182
In this article, we will walk through the process of implementing file upload functionality in an ASP.NET MVC application using a simple controller.
File Upload ASP.NET MVC
The example below will guide you through creating a form to upload a file, handling the file upload in the controller, and saving the uploaded file to a specific folder on the server.
You would start by creating an HTML form that includes a file input element for file selection.
Create a new view called Index.cshtml
in the Views/Home
folder.
1 2 3 4 5 |
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { < input type = "file" name = "file" /> < input type = "submit" value = "Upload" /> } |
Then, you would create a controller to handle the file upload.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class HomeController : Controller { // This action renders the form public ActionResult Index() { return View(); } // This action handles the form POST and the upload [HttpPost] public ActionResult Index(HttpPostedFileBase file) { // Verify that the user selected a file if (file != null && file.ContentLength > 0) { // extract only the filename var fileName = Path.GetFileName(file.FileName); // store the file inside ~/files folder var path = Path.Combine(Server.MapPath( "~/files" ), fileName); file.SaveAs(path); } // redirect back to the index action to show the form once again return RedirectToAction( "Index" ); } } |
When the user selects a file and submits the form, the file is sent to the server in the POST request and handled by the Index
POST action in the HomeController
. The HttpPostedFileBase
class is used to capture the uploaded file, and the SaveAs
method is used to save the file on the server.
- How to Initialize TagHelpers in ASP.NET Core with Shared Data
- Essential Tips for Securing Your ASP.NET Website
- Top Security Best Practices for ASP.NET
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy