How to Upload File in ASP.NET Core MVC

How to Upload File in ASP.NET Core MVC

In this article, I will discuss how to upload files in the ASP.NET Core MVC Application with examples of using buffering and streaming. In most of the applications, we can upload profile photos, which will be displayed to identify the user. For example, Facebook, WhatsApp, Twitter, and many more. This is a very basic feature: an 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.

  • Buffering
  • Streaming
Differences Between Buffering and Streaming in File Uploading in ASP.NET Core

In ASP.NET Core, the concepts of buffering and streaming are important to understand, especially in the context of file uploading. Here’s an overview of the differences:

Buffering in File Uploading:

Buffering refers to the process of reading an entire file into memory before being processed or uploaded. In ASP.NET Core, buffering can be achieved using the IFormFile interface when handling file uploads.

Advantages of Buffering:
  • Simplicity: Buffering is easier to implement as the entire file is available in memory, making it straightforward to work with.
  • Reliability: It can be more reliable for small files, as the server handles the entire file after it’s fully received.
Disadvantages of Buffering:
  • Memory Usage: Large files can consume significant memory, which might cause out-of-memory exceptions.
  • Performance: For large files, the server waits for the entire file to be uploaded before processing starts.
Streaming in File Uploading:

Streaming, in contrast, involves reading and processing a file in chunks as the data arrives. This can be done in ASP.NET Core using asynchronous streaming APIs.

Advantages of Streaming:
  • Efficiency with Large Files: Streaming is more memory-efficient for large files, as it doesn’t require loading the entire file into memory.
  • Better Performance: It allows the server to start processing data as soon as it starts receiving, leading to potentially faster processing times.
Disadvantages of Streaming:
  • Complexity: Implementing streaming is more complex than buffering, especially regarding error handling and ensuring data integrity.
  • Potential Latency Issues: The overhead of setting up a streaming process can outweigh its benefits for smaller files.
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 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. Finally, click on the Create button, as shown in the image below.

File Upload in ASP.NET Core MVC

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

How to Upload File in ASP.NET Core MVC

Creating File Upload Controller:

First, create an MVC Controller – Empty with the named FileUploadController. By default, this controller is created with the Index action method.

Adding the Index View:

In your MVC view, create a form with enctype=”multipart/form-data” to allow file uploads. Add an input of type file for users to select the file they want to upload. Let’s add the Index.cshtml file within the Views/FileUpload folder to add a form control. The form control encloses an input control of the type file, followed by a button control of the type submit. So, once you add the Index.cshtml file within the Views/FileUpload folder, then copy and paste the following code into it.

@{
    ViewData["Title"] = "File Upload Page";
}

<h2>Single File Upload</h2>
<hr />
<div class="row">
    <div class="col-md-12">
        <form method="post" asp-controller="FileUpload" asp-action="SingleFileUpload"
              enctype="multipart/form-data">
            <div asp-validation-summary="All" class="text-danger"></div>
            <input type="file" name="SingleFile" class="form-control" />
            <button type="submit" name="Upload" class="btn btn-primary">Upload</button>
        </form>
    </div>
</div>
Notice that
  1. Here, the form control has method = post, asp-controller=” FileUpload” asp-action=”SingleFileUpload” attributes. The SingleFileUpload action method in the FileUpload controller will be executed upon submission of the form.
  2. The name attribute of the file type input is SingleFile
Handling the File Upload in the Controller:

In your ASP.NET Core MVC controller, create an action method to handle the file upload. The method should be decorated with [HttpPost] to handle POST requests from the form. Use IFormFile to represent the uploaded file.

So, let’s modify the FileUpload controller to add a new action method, SingleFileUpload; in this action method, we have to save the file to the application root directory using the CopyToAsync(Stream) method of the IFormFile interface. So, modify the FileUpload controller as follows:

using Microsoft.AspNetCore.Mvc;

namespace FileUploadInMVC.Controllers
{
    public class FileUploadController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> SingleFileUpload(IFormFile SingleFile)
        {
            if (ModelState.IsValid)
            {
                if (SingleFile != null && SingleFile.Length > 0)
                {
                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", SingleFile.FileName);

                    //Using Buffering
                    using (var stream = System.IO.File.Create(filePath))
                    {
                        // The file is saved in a buffer before being processed
                        await SingleFile.CopyToAsync(stream);
                    }

                    //Using Streaming
                    //using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    //{
                    //    await SingleFile.CopyToAsync(stream);
                    //}

                    // Process the file here (e.g., save to the database, storage, etc.)
                    return View("UploadSuccess");
                }
            }

            return View("Index");
        }
    }
}
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.

Handling the File Upload in the Controller

Using the “CopyToAsync” method of the IFormFile instance, we are saving the file by passing the file stream object.

IFormFile Interface:

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.

IFormFile Interface

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.
Adding UploadSuccess View:

Next, add the UploadSuccess.cshtml view within the Views/FileUpload folder, and then copy and paste the following code into it.

@{
    ViewData["Title"] = "UploadSuccess";
}

<h1>File Uploaded Successfully</h1>
Creating Uploads Folder:

Create a folder named uploads within the wwwroot folder where all the uploaded images will be stored. Once you add the folder, it should look as shown below:

Creating Uploads Folder

Running the Application:

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

Running the Application

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 image below.

Differences Between Buffering and Streaming in File Uploading in ASP.NET Core

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 FileUpload Controller will be hit. Right-click on the SingleFile parameter and select the QuickWatch option from the context menu. Notice it contains all the details about the file we just uploaded, as shown below.

File Uploading in ASP.NET Core MVC using Buffering and Streaming

Click on F5 to continue with debugging. Once the file is copied to the specified path, it will be redirected to the UploadSuccess page, and we should be able to see the uploaded file in the Solution Explorer, as shown below.

File Uploading in ASP.NET Core MVC using Buffering and Streaming

When should you use File Upload in ASP.NET Core MVC?

File upload functionality is a common requirement in various types of web applications. Here are some scenarios where you might need to implement file upload:

  • Document Management Systems: For applications that manage documents (e.g., PDFs, Word documents), enabling users to upload their documents is essential.
  • User Profile Management: In systems where users can create and update profiles, allowing them to upload profile pictures or other personal documents.
  • E-commerce Websites: For product management, where sellers need to upload product images, specifications, or manuals.
  • Content Management Systems (CMS): Enabling content creators to upload multimedia files like images, videos, and audio files for blog posts, web pages, or galleries.
  • Data Import/Export Features: In applications that require data migration or bulk data operations, users can upload CSV, Excel, or XML files to import data.
  • Educational Platforms: Allowing students to upload assignments, projects, or other educational materials. Teachers can also upload educational content.
  • Social Media Platforms: Implementing features for users to upload photos, videos, or other media types to share with others.
  • Online Forms and Applications: In scenarios where users need to submit forms along with supporting documents, like in job applications, visa applications, or insurance claims.
  • Healthcare Applications: For patient management systems where patients can upload medical reports, prescriptions, or other healthcare-related documents.
  • Email and Communication Systems: Allowing users to attach files to emails or messages.
Considerations:
  • Security and Privacy: Always ensure the security of the file upload process to prevent unauthorized access and protect sensitive data. Implement measures to scan for malware in uploaded files and validate file types.
  • Performance: Large file uploads can impact the performance of your application. Implementing features like chunked file upload can be beneficial.
  • User Experience: Provide feedback to users during the upload process, such as progress bars or success/error messages.
  • Storage and Scalability: Consider where the files will be stored (e.g., server filesystem, cloud storage) and how your storage strategy will scale with increased usage.
  • Legal and Compliance: Be aware of legal requirements and compliance issues related to storing and handling user data, especially for sensitive information.

In the next article, I will discuss How to Restrict Uploaded File Size in the ASP.NET Core MVC Application with Examples. In this article, I try to explain How to Upload a Single File in the ASP.NET Core MVC Application with Examples using Buffering and Streaming. And I hope you enjoy this How to Upload a Single File in ASP.NET Core article.

1 thought on “How to Upload File in ASP.NET Core MVC”

  1. Collins Aigbekhai

    I am new to asp.net core, I have been trying to upload image using the knowledge I have with mvc with ado.net but it’s not working. I would like to learn more about using sql server ado.net in asp.net core, I am familiar with ado.net using mvc but asp.net core is quite different, I am also not very comfortable with ef programming, I would love if I can get some support.

Leave a Reply

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