How to Increase the max upload file size in ASP.NET MVC
By FoxLearn 2/18/2024 1:23:33 AM 66
By default, you only upload up to 4MB (4096 KB) when hosting your website on IIS.
To increase file size when uploading on IIS 7 you need to open the web.config file, then add the configuration as below.
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="52428800" /> </requestFiltering> </security> </system.webServer>
As you can see, I have increased the max file upload size to 50MB. You can also increase the maximun upload file size by creating a custom file size attribute as shown below.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web; using System.Web.Mvc; namespace Customs { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class FileSizeAttribute : ValidationAttribute, IClientValidatable { public int? MaxBytes { get; set; } public FileSizeAttribute(int maxBytes) : base("Please upload a supported file.") { MaxBytes = maxBytes; if (MaxBytes.HasValue) ErrorMessage = $"Please upload a file of less than {MaxBytes.Value} bytes."; } public override bool IsValid(object value) { HttpPostedFileBase file = value as HttpPostedFileBase; if (file != null) { bool result = true; if (MaxBytes.HasValue) result &= (file.ContentLength < MaxBytes.Value); return result; } return true; } IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = "filesize", ErrorMessage = FormatErrorMessage(metadata.DisplayName) }; rule.ValidationParameters["maxbytes"] = MaxBytes; yield return rule; } } }
Open the FilterConfig.cs file, then add FileSizeAttribute to the RegisterGlobalFilters method that lets you filter the upload file size to IIS.
using System.Web; using System.Web.Mvc; namespace CSharpCode { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new FileSizeAttribute()); } } }
- How to fix Font Awesome WebFont woff2 not working BundleConfig
- How to Minify HTML using WebMarkupMin in ASP.NET Core
- How to Minify HTML using WebMarkupMin in ASP.NET MVC
- How to Minify HTML output from ASP.NET MVC
- How to fix 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- The name 'Session' does not exist in the current context
- How to fix 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'
Categories
Popular Posts
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024
What Are RESTful Web Services?
02/19/2024