The size of an uploaded file is an important factor for considering the storage capacity. We cannot allow an infinite file size to be uploaded by the end-users because this will cause only one user to fill the server storage capacity in the worst case scenario. Well, that could cause a lot of issues at the back-end server. So, restricting or limiting the upload file size is one of the key business requirements of the web application. Sometimes, only image files are accepted by the web application, sometimes only documents, and sometimes the combination of image, documents, and compressed file types are accepted by the web system.
Today, I shall be demonstrating limiting/restricting of upload file size by implementing a custom data annotation/attribute component on ASP.NET MVC5 platform. This article is not specific to image files only, you can use the provided solution with any type of file format as well.
Prerequisites
Following are some prerequisites before you proceed any further in this tutorial.
- Knowledge of ASP.NET MVC5
- Knowledge of HTML
- Knowledge of Bootstrap
- Knowledge of C# Programming
You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.
Let's begin now.
Step 1
Step 2
- .....
- <system.web>
- <authentication mode="None" />
- <compilation debug="true" targetFramework="4.5.2" />
- <!-- executionTimeout = 30hrs (the value is in seconds) and maxRequestLength = 1GB (the value is in Bytes) -->
- <httpRuntime targetFramework="4.5.2" executionTimeout="108000" maxRequestLength="1073741824" />
- </system.web>
- <system.webServer>
- <!-- maxAllowedContentLength = 1GB (the value is in Bytes) -->
- <security>
- <requestFiltering>
- <requestLimits maxAllowedContentLength="1073741824" />
- </requestFiltering>
- </security>
- .....
- </system.webServer>
- .....
executionTimeout -> The amount of time required to process your request on the web server; The value is provided in seconds.
maxRequestLength -> The maximum size which your request can capture and send to the web server; The value is provided in bytes.
maxAllowedContentLength -> The maximum allowed size of your content (e.g. file, text data etc) to be sent to the web server; The value is provided in bytes.
Step 3
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- <!-- Font Awesome -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div>
- @*Scripts*@
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/jqueryval")
- @Scripts.Render("~/bundles/bootstrap")
- @RenderSection("scripts", required: false)
- </body>
- </html>
In the above code, I have simply created a basic default layout page and linked the require libraries into it.
Step 4
- //-----------------------------------------------------------------------
- // <copyright file="AllowFileSizeAttribute.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace ImgFileSizeLimit.Helper_Code.Common
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- /// <summary>
- /// Allow file size attribute class
- /// </summary>
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
- public class AllowFileSizeAttribute : ValidationAttribute
- {
- #region Public / Protected Properties
- /// <summary>
- /// Gets or sets file size property. Default is 1GB (the value is in Bytes).
- /// </summary>
- public int FileSize { get; set; } = 1 * 1024 * 1024 * 1024;
- #endregion
- #region Is valid method
- /// <summary>
- /// Is valid method.
- /// </summary>
- /// <param name="value">Value parameter</param>
- /// <returns>Returns - true is specify extension matches.</returns>
- public override bool IsValid(object value)
- {
- // Initialization
- HttpPostedFileBase file = value as HttpPostedFileBase;
- bool isValid = true;
- // Settings.
- int allowedFileSize = this.FileSize;
- // Verification.
- if (file != null)
- {
- // Initialization.
- var fileSize = file.ContentLength;
- // Settings.
- isValid = fileSize <= allowedFileSize;
- }
- // Info
- return isValid;
- }
- #endregion
- }
- }
In ASP.NET MVC5, creating customized data annotations/attributes is one of the cool features. In the above code, I have created a new class "AllowFileSizeAttribute" (by following the naming convention of custom attribute class) and inherited ValidationAttribute class. Then, I have created a public property "FileSize" and set its default value as 1 GB in bytes which means that my custom attribute will accept only uploaded files with a maximum file size less than or equal to 1 GB. So, in order to allow the required file size, this property will be updated at the time of my custom attribute utilization accordingly. Finally, I have overridden the "IsValid(....)" method which will receive my uploaded file as "HttpPostedFileBase" data type and from this, I will extract the file size of the upload file and then validated whether it is less than or equal to the default file size restriction or according to my provided file size.
Step 5oi
- //-----------------------------------------------------------------------
- // <copyright file="ImgViewModel.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace ImgFileSizeLimit.Models
- {
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Web;
- using Helper_Code.Common;
- /// <summary>
- /// Image view model class.
- /// </summary>
- public class ImgViewModel
- {
- #region Properties
- /// <summary>
- /// Gets or sets Image file.
- /// </summary>
- [Required]
- [Display(Name = "Upload File")]
- [AllowFileSize(FileSize = 5 * 1024 * 1024, ErrorMessage = "Maximum allowed file size is 5 MB")]
- public HttpPostedFileBase FileAttach { get; set; }
- /// <summary>
- /// Gets or sets message property.
- /// </summary>
- public string Message { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether file size is valid or not property.
- /// </summary>
- public bool IsValid { get; set; }
- #endregion
- }
- }
In the above code, I have created my View Model which I will attach with my View. Here, I have created HttpPostedFileBase type file attachment property which will capture the uploaded image/file data from the end-user. Then, I have also applied my custom "AllowFileSize" attribute to the FileAttach property and provided the default file size as 5 MB that I have allowed my system to accept. Then, I have created two more properties, i.e., Message of data type string and isValid of data type Boolean for processing purpose.
Step 6
- //-----------------------------------------------------------------------
- // <copyright file="ImgController.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace ImgFileSizeLimit.Controllers
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Models;
- /// <summary>
- /// Image controller class.
- /// </summary>
- public class ImgController : Controller
- {
- #region Index view method.
- #region Get: /Img/Index method.
- /// <summary>
- /// Get: /Img/Index method.
- /// </summary>
- /// <returns>Return index view</returns>
- public ActionResult Index()
- {
- // Initialization/
- ImgViewModel model = new ImgViewModel() { FileAttach = null, Message = string.Empty, IsValid = false };
- try
- {
- }
- catch (Exception ex)
- {
- // Info
- Console.Write(ex);
- }
- // Info.
- return this.View(model);
- }
- #endregion
- #region POST: /Img/Index
- /// <summary>
- /// POST: /Img/Index
- /// </summary>
- /// <param name="model">Model parameter</param>
- /// <returns>Return - Response information</returns>
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Index(ImgViewModel model)
- {
- try
- {
- // Verification
- if (ModelState.IsValid)
- {
- // Settings.
- model.Message = "'" + model.FileAttach.FileName + "' file has been successfuly!! uploaded";
- model.IsValid = true;
- }
- else
- {
- // Settings.
- model.Message = "'" + model.FileAttach.FileName + "' file size exceeds maximum limit. ";
- model.IsValid = false;
- }
- }
- catch (Exception ex)
- {
- // Info
- Console.Write(ex);
- }
- // Info
- return this.View(model);
- }
- #endregion
- #endregion
- }
- }
In the above code, I have created the GET "Index(...)" method which will initialize the View Model with default values and sent it to the View page. Finally, I have created the POST "Index(...)" method which will receive an input file from the end-user, then validated the View Model for allowed file size and then sent the response message accordingly.
Step 7
- @using ImgFileSizeLimit.Models
- @model ImgFileSizeLimit.Models.ImgViewModel
- @{
- ViewBag.Title = "ASP.NET MVC5: Limit Upload File Size";
- }
- <div class="row">
- <div class="panel-heading">
- <div class="col-md-8">
- <h3>
- <i class="fa fa-file-text-o"></i>
- <span>ASP.NET MVC5: Limit Upload File Size</span>
- </h3>
- </div>
- </div>
- </div>
- <br />
- <div class="row">
- <div class="col-md-6 col-md-push-2">
- <section>
- @using (Html.BeginForm("Index", "Img", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form" }))
- {
- @Html.AntiForgeryToken()
- <div class="well bs-component">
- <br />
- <div class="row">
- <div class="col-md-12">
- <div class="col-md-8 col-md-push-2">
- <div class="input-group">
- <span class="input-group-btn">
- <span class="btn btn-default btn-file">
- Browse…
- @Html.TextBoxFor(m => m.FileAttach, new { type = "file", placeholder = Html.DisplayNameFor(m => m.FileAttach), @class = "form-control" })
- </span>
- </span>
- <input type="text" class="form-control" readonly>
- </div>
- @if (Model.IsValid && !string.IsNullOrEmpty(Model.Message))
- {
- <span class="text-success">@Model.Message</span>
- }
- else
- {
- <span class="text-danger">@Model.Message</span>@Html.ValidationMessageFor(m => m.FileAttach, "", new { @class = "text-danger" })
- }
- </div>
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-12">
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-5 col-md-10">
- <input type="submit" class="btn btn-danger" value="Upload" />
- </div>
- </div>
- </div>
- }
- </section>
- </div>
- </div>
- @section Scripts
- {
- @*Scripts*@
- @Scripts.Render("~/bundles/bootstrap-file")
- @*Styles*@
- @Styles.Render("~/Content/Bootstrap-file/css")
- }
In the above code, I have created a simple View for uploading the file to the server which will validate the allowed file size at the server side.
Step 8



So, when I try to upload a file with a size greater than 5 MB, I will receive the error message like below.


In this article, we learned about limiting/restricting the desired upload file size by implementing custom data annotation/attribute component on ASP.NET MVC5 platform. Also, we saw how to create a custom data annotation/attribute class and then utilize the custom attribute in our View Model property of type HttpPostedFileBase.

Mohamed Abdel GhafourPosted Jan 17, 2021, 10:01 AM
Thank you ......
Hamid KhanPosted Sep 7, 2019, 11:04 PM
Very good explanation...…...
Armando APosted Jun 24, 2019, 4:47 PM
Cool article, very clear, just another question, how do you validate the file name and full path? I know that browsers have a limit of 255 characters (i think that is the exact number) and if you have one larger than that, the file will not be uploaded.
Rushi MehtaPosted Dec 23, 2018, 11:26 PM
Nicely Explained.. Thanks for sharing the code ..
Alice NguyenPosted Dec 21, 2018, 1:09 AM
Very well explained! Thanks