How to Implement File Upload in ASP.NET MVC

By FoxLearn 12/5/2024 11:15:46 AM   42
To implement file upload in ASP.NET MVC, follow these steps.

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.

@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.

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.