I have an ASP.Net MVC web application that needs to handle file uploading with progress.
To achieve this I have created a custom IHttpHandler
that process the file stream in chunks using the ProcessRequest
method. The implementation of this is not important for my issue.
Client side I am using JQuery to upload the file with the AJAX function, something like this:
$.ajax({
url: '@Url.RouteUrl("Uploads")',
type: 'POST',
headers: { 'Filename': file.name },
data: formData,
cache: false,
contentType: false,
processData: false,
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
myXhr.addEventListener('load', function (e) {
console.log('upload complete');
});
return myXhr;
}
});
I have configured the upload/request limits in the web.config to allow files up to 2GB, which as far as I can tell is a hard limit in IIS anyway.
Problem
The problem I have is that when a user tries to upload a file larger than the limit it doesn't throw an error until the whole file has been transferred, which can take a few minute for large files. The is an undesired user experience for the user to have to wait for the transfer to complete before being told it cannot be processed.
Question
So my question is, is there anyway to get the ajax function to error as soon as the upload starts in the event the file is too large? Ideally I don't want the file to be sent to the server if it's only going to be rejected anyway.
Additional Information
For additional info, a breakpoint in the IHttpHandler code is only ever hit when the file size is within the limit, so I can't do anything in there to throw an error.
Note that I am not looking for a solution that involves checking the file size using javascript on the client size. Although I will probably use this as a user friendly precaution anyway, I want to find a method that causing the upload process to fail and abort before all the data is sent. I am however open to client side changes that don't rely on file size checking, for example alternate option for the ajax function.
I have also tried playing around with Application_BeginRequest()
but this doesn't get called if the file is larger than 2GB, and I am not sure there is another event that I can check that happens before this.