How to Restrict Uploaded File Type in ASP.NET Core MVC

SPONSOR AD

How to Restrict Uploaded File Type in ASP.NET Core MVC

In this article, I will discuss How to Restrict Uploaded File Types in an ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to Restrict Uploaded File Size in ASP.NET Core MVC Application with Examples. Let’s continue with the application we worked on in previous articles.

How do you restrict the uploaded file type in ASP.NET Core MVC?

Restricting the file type of uploaded files in ASP.NET Core MVC is an important security measure to prevent users from uploading potentially harmful files to your server. Here’s how you can achieve this:

Validating File Extension and MIME Type in the Controller:

When handling the file upload in your controller action method, you can check the file extension and MIME type to ensure it’s permitted.

[HttpPost]
// [RequestSizeLimit(10000000)] // Limit to 10 MB
public async Task<IActionResult> SingleFileUpload(IFormFile SingleFile)
{
    if (SingleFile == null || SingleFile.Length == 0)
    {
        ModelState.AddModelError("", "File not selected");
        return View("Index");
    }

    var permittedExtensions = new[] { ".jpg", ".png", ".gif" };
    var extension = Path.GetExtension(SingleFile.FileName).ToLowerInvariant();

    if (string.IsNullOrEmpty(extension) || !permittedExtensions.Contains(extension))
    {
        ModelState.AddModelError("", "Invalid file type.");
    }

    // Optional: Validate MIME type as well
    var mimeType = SingleFile.ContentType;
    var permittedMimeTypes = new[] { "image/jpeg", "image/png", "image/gif" };
    if (!permittedMimeTypes.Contains(mimeType))
    {
        ModelState.AddModelError("", "Invalid MIME type.");
    }

    //Validating the File Size
    if (SingleFile.Length > 10000000) // Limit to 10 MB
    {
        ModelState.AddModelError("", "The file is too large.");
    }

    if (ModelState.IsValid)
    {
        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");
}

Now, run the application and upload a PDF file, and you should see the following error message.

SPONSOR AD

How to Restrict Uploaded File Types in an ASP.NET Core MVC Application with Examples

Client-Side Validation (Optional but Recommended):

While server-side validation is essential, you can also implement client-side validation to provide immediate feedback to the user. This can be done using JavaScript or by specifying the accept attribute in your HTML form. So, modify the index.cshtml view as follows:

@{
    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" accept=".jpg,.png,.gif" class="form-control" />
            <button type="submit" name="Upload" class="btn btn-primary">Upload</button>
        </form>
    </div>
</div>

Once you run the application, you will only see the file type to be uploaded, which is allowed. You cannot see the PDF file option now.

Why Restrict Uploaded File Type in an ASP.NET Core MVC?

Restricting the types of files that users can upload in an ASP.NET Core MVC application is crucial for several important reasons. Here are scenarios and justifications for implementing file type restrictions:

  • Security: Limiting file types helps prevent the upload of malicious files. For instance, executable files (.exe, .bat, etc.) can contain harmful scripts or software. By allowing only specific file types, such as images or documents, you reduce the risk of malware and other security threats.
  • Application Specificity: Certain applications only need specific types of files. For instance, a photo gallery app should accept image files only, or a document management system might only require PDFs and Word documents.
  • Data Consistency and Integrity: Restricting file types ensures that only appropriate and expected types of data are stored. This maintains data consistency in your system, especially if the files are to be processed or displayed later.
  • System Performance: Certain file types might be resource-intensive to process or display. By restricting file types, you can avoid unnecessary strain on your server resources.
  • User Experience: Limiting file types helps users understand what is acceptable to upload, potentially reducing confusion and errors during the upload process. This can enhance the overall user experience.
  • Storage Management: Different file types can have vastly different sizes. Restricting file types can indirectly help manage storage usage, especially if certain unrestricted file types tend to be large (like video files).
  • Legal and Compliance: Certain types of content might not be legally permissible to upload or store, depending on the application’s purpose and its requirements.
  • File Processing Requirements: Your application might process uploaded files in specific ways. For example, if your application includes file processing (like image resizing and document conversion), you must restrict uploads to file types that your processing tools can handle.
Best Practices:
  • Always perform server-side validation even if you have client-side checks.
  • Provide clear error messages to inform users about the allowed file types.
  • Regularly review and update the list of permitted file types based on the application’s evolving needs and security requirements.
  • Consider scanning for malware in uploaded files, especially if other users or administrators will access them.

In the next article, I will discuss How to Save the Uploaded file to a Database in an ASP.NET Core MVC Application with Examples. In this article, I try to explain How to Restrict Uploaded File Types in the ASP.NET Core MVC Application with Examples. And I hope you enjoy this article.

SPONSOR AD

Leave a Reply

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