Grails 3.3.x handle file upload max size exceeded exception

244 views Asked by At

I'm reading this tutorial on file uploads: https://guides.grails.org/grails-upload-file/guide/index.html

But even if the file size limit is set to 25MB, there is no description of how to handle the FileUploadBase$SizeLimitExceededException exception when the file uploaded is greated than that. If there is a limit, even if it's too big, someone will hit it and would like to show a nice error to the user, but the exception seems to happen before executing my controller's code.

The question is: how to handle that kind of exception on a Grails 3.3.x app?

1

There are 1 answers

1
Joe On

I think after 2MB file size the James Kleeh solution has issues with Tomcat max-swallow-size causing multiple exceptions.

https://github.com/grails/grails-core/issues/9378

I went ahead and used Javascript and at least did a client side validation. See below:

function validateSize() {
    var fileSize = document.getElementById("uploadFile").files[0];
    var sizeInMb = (fileSize.size / 1024) / 1024;
    var sizeLimit = 10;
    if (sizeInMb > sizeLimit) {
        alert('File size must be less than 10 MB');
        return false;
    }
    showSpinner();
    return true;
}

<input type="submit" value="I Accept" class="btn btn-success" onclick="return validateSize()"/>