How to upload files in ASP.NET MVC?


In this article, you will learn how to upload a document in an ASP.NET MVC application using C#.

ASP.NET MVC provides a convenient way to handle file uploads in web applications. We can create a controller to handle the file upload functionality and a view to display the appropriate messages.

Let’s implement the file-uploading functionality step-by-step.

Create a Controller to Upload Files

The first step is to create a controller that will handle the file upload functionality. We will create an Index action method to display the UploadFile view and a POST action method to handle the actual file upload.

The following example demonstrates how to create an UploadFile controller with the necessary action methods:

UploadFileController.cs
public class UploadFileController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        try
        {
            // Handle file upload logic here
            if (file != null && file.ContentLength > 0)
            {
                string fileExtension = Path.GetExtension(file.FileName);
                string[] allowedExtensions = { ".pdf", ".doc", ".docx" };

                if (allowedExtensions.Contains(fileExtension))
                {
                    var maxFileSize = 5 * 1024 * 1024; // 5MB
                    if (file.ContentLength > maxFileSize)
                    {
                        ViewBag.Message = "File size exceeds the maximum limit of 5MB.";
                        return View();
                    }


                    // Save the file to the server or perform any other necessary operations
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
                    file.SaveAs(path);

                    // Display success message
                    ViewBag.Message = "File uploaded successfully!";
                }
                else
                { 
                    ViewBag.Message = "Only pdf, doc and docx files are allowed.";

                }
            }
            else
            {
                // Display error message
                ViewBag.Message = "Please select a file to upload.";
            }
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message;
        }

        return View();
    }
}

In the above example:

  • The Index action method simply returns the Index.cshtml view.
  • The [HttpPost] attribute over the Upload action method specifies that the action method can only be invoked for HTTP POST requests.
  • The [ValidateAntiForgeryToken] attribute helps protect against Cross-Site Request Forgery (CSRF) attacks by ensuring that the form data includes a valid anti-forgery token. The token is generated in the
  • Inside the try block, the code checks whether a file has been provided in the HTTP request and if its content length is greater than 0, indicating that a file has been selected for upload. It then proceeds to validate the file extension by checking if it matches one of the allowed extensions (.pdf, .doc, .docx). If the file has an allowed extension, it proceeds to check the file size.
  • The maximum allowed file size is set to 5 megabytes (5 * 1024 * 1024 bytes). If the file exceeds this size limit, an error message is set in the ViewBag, and the action method returns the same view to display the error message to the user.
  • If the file passes all validation checks, it is saved to the server under the "~/App_Data/Uploads" directory. The file name is preserved, and the file is saved with the file.SaveAs(path).
  • Appropriate messages are set in the ViewBag based on the outcome of the file upload operation. These messages will be displayed to the user in the view.

Create Views to Upload Files

Next, we need to create two views to display the file upload form and the appropriate messages. The view should have a form with an input field of type "file" to allow the user to select a file for upload.

Here's an example of how the Index.cshtml view could look like:

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

In the above example:

  • We use the Html.BeginForm helper method to create a form that will submit the file to the Upload action method of the UploadFile controller.
  • The enctype attribute is set to "multipart/form-data" to allow file uploads.

Next, we need to create an upload.cshtml view to display an appropriate message, as shown below.

Upload.cshtml
<h1>File Upload Status</h1>

@if (!string.IsNullOrEmpty(ViewBag.Message))
{
    <div>@ViewBag.Message</div>
}

Upload another file

Now, you can upload a file by following steps:

  1. Visit https://localhost:xxxx/uploadfile
  2. Browse for the file and click on the Upload button.
  3. It will call the Upload() action method with file content and save the file to the “/App_Data/Uploads” folder (make sure you have created the Uploads folder) and display a success message.
  4. If there is any error then it will display an error message.

Upload Multiple Files

To handle multiple file uploads, we can modify the Upload action method to accept an array or a list of HttpPostedFileBase objects. We can then loop through the files and perform the necessary operations.

Here's an example of how the modified Upload action method could look like:

Example: Upload Multiple Files
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        if (file != null && file.ContentLength > 0)
        {
            // Save each file to the server or perform any other necessary operations
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
            file.SaveAs(path);
        }
    }

    // Display success message
    ViewBag.Message = "Files uploaded successfully!";

    return View("Index");
}

In this way, you can implement file uploading functionality in ASP.NET MVC application.