Grails3 file upload maxFileSize limit
Solution 1:
Grails 3 and 4
The solution is to set maxFileSize
and maxRequestSize
limits inside your application.yml
file. Be sure to have something like this:
grails:
controllers:
upload:
maxFileSize: 2000000
maxRequestSize: 2000000
Replace 2000000
with the number of max bytes you want for a file upload and for the entire request. Grails 3 and Grails 4 default is 128000 (~128KB).
FAQ
1. How to convert from MB to bytes?
YOUR_MAX_SIZE_IN_MB * 1024 * 1024 = BYTES
E.g. Convert 5 MB in bytes
5 * 1024 * 1024 = **5242880** bytes
2. Security
As quote from OWASP
Limit the file size to a maximum value in order to prevent denial of service attacks
So these limits exist to prevent DoS attacks and to enforce overall application performance (bigger request size == more memory used from the server).
3. What is the right value for maxFileSize
and maxRequestSize
?
It depends on the application type, but it's generally a bad idea to keep them too high. If you really need to upload big files, probably you should develop (or use) a dedicated (and separated) service.
Solution 2:
Part of the problem is setting a max file size. The other problem is handling that error gracefully.
Here is my bean definition:
multipartResolver(MyMultipartResolver) {
maxUploadSize = (5*1024*1024)
}
Here is my implementation:
public class MyMultipartResolver extends CommonsMultipartResolver {
static final String FILE_SIZE_EXCEEDED_ERROR = "fileSizeExceeded";
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) {
try {
return super.resolveMultipart(request);
} catch (MaxUploadSizeExceededException e) {
request.setAttribute(FILE_SIZE_EXCEEDED_ERROR, true);
return new DefaultMultipartHttpServletRequest(request, new LinkedMultiValueMap<String, MultipartFile>(), new LinkedHashMap<String, String[]>(), new LinkedHashMap<String, String>());
}
}
}
The idea being to check for the request attribute in your controller or a filter to determine if the file was too large.
Solution 3:
I also had no luck trying to set new maximum values in application.properties or application.yml.
What does work though is using a bean definition in conf/spring/resources.groovy:
import javax.servlet.MultipartConfigElement
// Place your Spring DSL code here
beans = {
multipartResolver(org.springframework.web.multipart.commons.CommonsMultipartResolver){
maxInMemorySize=1000000
maxUploadSize=100000000
//uploadTempDir="/tmp"
}
}
Solution 4:
Try this https://github.com/zyro23/grails-core-668/blob/master/grails-app/conf/application.yml
upload: maxFileSize: 9999999999 maxRequestSize: 9999999999
Solution 5:
https://github.com/grails/grails-core/issues/668
grails.controllers.upload.maxFileSize
and/or
grails.controllers.upload.maxRequestSize
config properties/settings