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");
}
}
}
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>