Uploading Single File in ASP.NET Core MVC

File Upload in ASP.NET Core MVC

In this article, I am going to discuss How to Upload a Single File in ASP.NET Core MVC Application with Examples. In most of the applications, we have the option to upload profile photos which will be displayed to identify the user. For example, Facebook, WhatsApp, Twitter, and many more. This basic feature is to have the option to upload the photo, which will be saved and displayed in an application.

ASP.NET core MVC provides multiple ways to upload, process, and save files. It supports uploading single and multiple files. ASP.NET core MVC provides two general ways to upload files.

  1. Buffering
  2. Streaming
Buffering in ASP.NET Core MVC to Upload File

In this approach, the entire file is read into an IFormFile. IFormFile is a C# representation of the file used to process or save the file. The IFormFile represents a file sent with the HTTP Request. Use this approach to upload files of relatively smaller sizes. If you go to the definition of IFormFile, you will see that it is an interface with many properties and methods, as shown in the image below.

Buffering in ASP.NET Core MVC to Upload File

The details about the properties and the methods of the “IFormFile” interface as given by Microsoft are as follows:

Properties of IFormFile Interface:
  1. ContentType { get; }: Gets the raw Content-Type header of the uploaded file.
  2. ContentDisposition { get; }: Gets the raw Content-Disposition header of the uploaded file.
  3. Headers { get; }: Gets the header dictionary of the uploaded file.
  4. Length { get; }: Gets the file length in bytes.
  5. Name { get; }: Gets the form field name from the Content-Disposition header.
  6. FileName { get; }: Gets the file name from the Content-Disposition header.
Methods of IFormFile Interface:
  1. CopyTo(Stream target): Copies the uploaded file’s contents to the target stream. Here, the parameter target specifies the stream to copy the file contents.
  2. CopyToAsync(Stream target, CancellationToken cancellationToken = default): Asynchronously copies the uploaded file’s contents to the target stream. Here, the parameter target specifies the stream to copy the file contents.
  3. OpenReadStream(): Opens the request stream for reading the uploaded file.
Streaming in ASP.NET Core MVC to Upload File

This approach is useful when you want to handle large files efficiently without loading the entire file into memory. Instead of using the “IFormFile” interface, you can directly read the uploaded file as a stream and process it accordingly.

In this article, we will see how to implement the file upload feature to upload a single file and how to process and save the file using the buffering approach in ASP.NET 6 MVC application.

In this example, we add a form control to the index.cshtml file within the Views –> Home folder. Add the file upload control and submit button within the form. In the home controller, add an action method for form submission. In the action method, we save the uploaded file.

Create ASP.NET 6 MVC Application using Visual Studio 2022

To create an ASP.NET Core Web Application with the MVC Project template. First, open Visual Studio 2022 and then click on the Create a new project tab, as shown in the image below.

Create ASP.NET 6 MVC Application using Visual Studio 2022

Once you click on the Create a new Project tab, it will open the following Create a new Project window. From this window, select “C#,” “All platforms,” and “Web” from respective dropdowns as highlighted below. Select “ASP.NET Core Web App (Model-View-Controller)” as highlighted below, and click on the “Next” button as shown in the below image.

Create ASP.NET 6 MVC Application using Visual Studio 2022
Once you click on the Next button, it will open the Configure Your New Project window. Here, you need to provide the necessary information to create a new ASP.NET Core project. First, give an appropriate name for your project (FileUploadInMVC), set the location where you want to create this project, and the solution name for the ASP.NET Core Web application. And finally, click on the Create button, as shown in the image below.

Create ASP.NET 6 MVC Application using Visual Studio 2022

Once you click on the create button, it will open the following Additional Information window. Here, you need to select Framework – .NET 6.0 (Long-term support), Authentication type – None. You also need to check the Configure for HTTPS and Do not use top-level statements check boxes, and finally, click on the Create button as shown in the below image.

Create ASP.NET 6 MVC Application using Visual Studio 2022

That’s it. Once you click on the Create Button, the project is going to be created with the Web Application (Model-View-Controller), i.e., MVC template, with the following folder and file structure.

Create ASP.NET 6 MVC Application using Visual Studio 2022

Let’s update the Index.cshtml file under Views => Home folder to add a form control. The form control encloses an input control of the type file and is followed by a button control of type submit, as shown below

How to Upload a Single File in ASP.NET Core MVC Application with Examples

Notice that

  1. form control has method = post, asp-controller=”Home” asp-action=”SingleFileUpload” attributes. The SingleFileUpload action method in the Home Controller will be executed on submitting the form.
  2. The name attribute of the file type input is SingleFile

So, open the Index.cshtml file and then copy and paste the following code into it.

@{
    ViewData["Title"] = "Home Page";
}

<form method="post" asp-controller="Home" asp-action="SingleFileUpload"
      enctype="multipart/form-data">
    <input type="file" name="SingleFile" />
    <button type="submit" name="Upload">Upload</button>
</form>
Modifying the Home Controller:

Let’s update the Home controller to add a new action method SingleFileUpload; in this action method, we save the file to the application root directory using the CopyTo(Stream) method of the IFormFile interface, as shown in the below code.

How to Upload a Single File in ASP.NET Core MVC Application with Examples

Notice that

We have an input parameter of type IFormFile for the action method. The name of the input parameter is SingleFile. The name of the input parameter must match the name of the file type input control that we have added.

How to Upload a Single File in ASP.NET Core MVC Application

We are creating a file stream that takes in the file path, file mode, and file access parameters.

  • File Path – In the content root directory, we are saving the uploaded file as file.png. Here we get the content root directory using the ContentRootPath property of IWebHostEnvironment.
  • File mode – Create
  • File Access – Write

Using the CopyTo method of the IFormFile instance, we save the file by passing the file stream. To get the content root path, we are using IWebHostEnvironment and getting the instance of it using dependency injection, as shown below.

How to Upload a Single File in ASP.NET Core MVC Application

So, with the above changes in place, open Home Controller and then copy and paste the following code into it.

using FileUploadInMVC.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace FileUploadInMVC.Controllers
{
    public class HomeController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        public HomeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult SingleFileUpload(IFormFile SingleFile)
        {
            using var fileStream = new FileStream
            (
                Path.Combine(_environment.ContentRootPath, "file.png"),
                FileMode.Create, 
                FileAccess.Write
             );

            SingleFile.CopyTo(fileStream);

            return RedirectToAction("Index");
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Now run the application, and the index view of the home controller will be displayed, as shown below. The index view has file type input control and a submit button which we added as shown below.

How to Upload a Single File in ASP.NET Core MVC

Click on Choose File and select a “*.png” file. After selecting, the file name will be displayed, and then click on the Upload button as shown in the below image.

Upload a Single File in ASP.NET Core MVC

Please put a breakpoint at the entry of the SingleFileUpload action method. Once you click on the Upload button, the SingleFileUpload action method of the HomeController will be hit. Right-click on the SingleFile parameter and then select the QuickWatch option from the context menu, as shown in the below image.

File Upload in ASP.NET Core MVC

Notice it contains all the details about the file we just uploaded, as shown below.

File Upload in ASP.NET Core MVC

Click on F5 to continue with debugging. Once the file is copied to the specified path, the index page will be reloaded, and we should be able to see the uploaded file in the solution explorer, as shown below.

File Upload in ASP.NET Core MVC

After saving the file, we re-direct the application to the index page.

ASP.NET Core MVC File Upload

This article discussed the file upload feature in ASP.NET Core MVC. We created a sample ASP.NET 6 MVC application and learned how to upload a single file, process and save it.

Let me know your thoughts on this in the comment section. In the next article, we will learn about uploading multiple files in ASP.NET Core MVC. In this article, I try to explain How to Upload a File in ASP.NET Core MVC Application with Examples. And I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *