How to Increase the max upload file size in ASP.NET MVC
By FoxLearn 2/18/2024 1:23:33 AM 385
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 securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
- How to Create a custom model validation attribute in ASP.NET Core
- How to disable ModelStateInvalidFilter in ASP.NET Core
- How to fix LoginPath not working in ASP.NET Core
- Synchronous operations are disallowed
Categories
Popular Posts
Portal HTML Bootstrap
11/14/2024
Carpatin Admin Dashboard Template
11/17/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024