How to upload file in ASP.NET MVC

By FoxLearn 11/15/2024 9:46:30 AM   84
To upload a file in an ASP.NET MVC application, you need to use the HttpPostedFileBase class to handle the file uploaded by the user.

To handle file uploads in ASP.NET MVC, you would start by creating an HTML form with a file input field. The form should have the enctype="multipart/form-data" attribute to allow file data to be sent along with the request. This is necessary because file uploads involve binary data, which needs to be encoded in a specific way when sent to the server.

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

How to POST a file to ASP.NET MVC?

In the controller, you'll use the HttpPostedFileBase parameter to access the uploaded file.

public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and upload file asp.net
    [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 ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            // upload file asp.net
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }
}

By default, ASP.NET MVC has a maximum request length of 4MB for file uploads (maxRequestLength = 4096), which means any file larger than 4MB will be rejected.

To allow larger file uploads, you need to update the web.config file by increasing the value of the maxRequestLength parameter under the <httpRuntime> element.

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="10240" executionTimeout="3600" />
  </system.web>
</configuration>

Add or modify the <httpRuntime> element to set a higher value for maxRequestLength and, if necessary, adjust the executionTimeout for longer processing times.

This change allows users to upload larger files by increasing the maximum allowed request size in your ASP.NET MVC application.