0

So I am getting the error "HTTP Error 413.1 - Request Entity Too Large" because I am attempting to upload a very large file. When I get this error, the whole site crashes to display that error page. On every SO or online post regarding this issue, the answer is to just increase the size of the allowed files in IIS configuration.

I want to keep the default size and rather just throw an error to the user letting them know their file is too big without crashing the site and displaying the HTTP Error 413.1 page. Is this possible to do? I was thinking of doing an error check in my view model but it didn't work.

public class uploadVM: IValidatableObject
{
    public IFormFile upload { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var size = upload.Length;
        if (size > 5242880)
        {
            yield return new ValidationResult("File upload too large");
        }
    }
}
Forrest
  • 157
  • 14

1 Answers1

1

I think this is because the asp.net core application is hosted in IIS, which will cause IIS to verify the uploaded file first. If it is too large, IIS will report an error directly. The solution I thought of is that you can use JS to judge the size of the uploaded file, and if the file is too large, don't pass it to the application in IIS.

 <script type="text/javascript">
var files = document.getElementById('fileId').files;  
var fileSize = 0;
if(files.length!=0){
    fileSize = files[0].size;
}
if(fileSize >1048576){
    alert("The uploaded file is too large!");
    return false;
}
 </script>
Ding Peng
  • 3,702
  • 1
  • 5
  • 8
  • So you don't believe it is possible to write something on the server side in order to block a file that is too large? – Forrest Jan 07 '21 at 14:47
  • Yes, Because the request will be processed by IIS first and then to the Asp.net core application, I don’t think it will work if the request is processed in Asp.net core. – Ding Peng Jan 08 '21 at 01:43