1

In my case, I am working on ASP.NET Core 5 project and I need to limit the maximum size for the entire form content to 2MB.

I have added the following attribute to my controller

[RequestFormLimits(ValueLengthLimit = 1024 * 1024 * 2)]
public class MyController : Controller
{
  ...
}

but the problem is that anytime a user tries to upload an image or any other form item that makes the entire content of the form to be more than 2MB, the application returns a 404 error.

I am looking for a way to rather display an error message when the entire content of the form exceeds 2MB.

I will appreciate any guide to handle this error gracefully instead of the 404 error it currently displays to users

Thank you

Josh
  • 1,660
  • 5
  • 33
  • 55

1 Answers1

1

On the client side you can do something similar to this to check for file size:

$("input[type='file']").on("change", function () {
    if (this.files[0].size > 2000000000) {
        alert("Please upload a file less than 2GB.");
        $(this).val('');
    }
   }

On the server side you can have a property IFormFile and check the size. file.FormFile.Length > 5 * 1024 * 1024;

Or you can create a custom Validation Attribute which I prefer. This should help you get started. https://stackoverflow.com/a/56592790/9936356

LinkedListT
  • 681
  • 8
  • 24
  • This is a great answer. It is very enlightening. Please, is there a way to make the custom validation or client side validation for the entire form, instead of for just a file field in the form? I need to control the max size of the entire form. – Josh Jan 10 '21 at 18:04
  • take a look at this for Model validation https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0. and take a look at this for file uploading https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1 – LinkedListT Jan 10 '21 at 18:08
  • None of those links talks about or solves my problem – Josh Jan 10 '21 at 18:34