上传MultipartFile时未捕获SizeLimitExceededException

时间:2018-09-15 15:03:33

标签: grails groovy

当我上传大文件时,我想捕获异常SizeLimitExceededException。 但是,我在控制器中创建了一个方法来捕获此异常,但是他返回了:

Error 500: Internal Server Error
URI
/user/uploadProfileImage
Class
org.apache.tomcat.util.http.fileupload
.FileUploadBase$SizeLimitExceededException
Message
Could not parse multipart servlet request; nested exception is 
java.lang.IllegalStateException: 
org.apache.tomcat.util.http.fileupload
.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (310380) exceeds the configured maximum (128000)
Caused by
the request was rejected because its size (310380) exceeds the configured maximum (128000)

捕获异常的方法:

def handleSizeLimitExceededException(FileUploadBase.SizeLimitExceededException ex){
     render(['error':true, message:ex.getMessage()] as JSON)
}

我的控制器:

class UserController {
...
    def uploadProfileImage(ProfileImageCommand cmd) {
        if (cmd.hasErrors()) {
                //respond(cmd, model: [user: cmd], view: 'create')
                response.status = 500
                render(['error':true, message:cmd.getErrors()] as JSON)
            }

        String filename = uploadFileService.uploadFileInTemp(cmd, relativePathTmp)

        Locale locale = request.locale
        //flash.message = crudMessageService.message(CRUD.UPDATE, domainName(locale), pointOfInterest.id, locale)
        render(['filename':filename, 'url': uploadFileService.getUrl(filename, relativePathTmp)] as JSON)
    }

    def handleSizeLimitExceededException(FileUploadBase.SizeLimitExceededException ex){
        render(['error':true, message:ex.getMessage()] as JSON)
    }
}

我的可验证者:

class ProfileImageCommand implements Validateable {
    MultipartFile imageFile

    static constraints = {
        imageFile  validator: { val, obj ->
            if ( val == null ) {
                return false
            }
            if ( val.empty ) {
                return false
            }

            ['jpeg', 'jpg', 'png'].any { extension ->
                val.originalFilename?.toLowerCase()?.endsWith(extension)
            }
        }
    }
}

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您没有提到Grails版本。我假设它的3 +

在application.yml中,您可以使用这些设置来设置要上传的文件的最大大小。

grails:
controllers:
        upload:
            maxFileSize: 20000000
            maxRequestSize: 20000000

此示例将请求和文件大小都设置为20MB。您可以根据需要进行调整。