0

I need to do a validation on file size in spring MultipartFile in a spring boot application. For example I want to restrict files upload more than 10MB. So i used below in application.yml,

servlet:
        multipart:
            max-file-size: 10MB
            max-request-size: 10MB

The problem I noticed it, when a request hits looks like it upload the whole 10MB and then only it throws the exception java.lang.IllegalStateException: io.undertow.server.RequestTooBigException

I am thinking a more efficient way as in with out request holding for whole 10MB is uploaded and throwing the exception before that it spring could do the validation may be look at meta data of file going to upload and throw the exception?

Harshana
  • 7,297
  • 25
  • 99
  • 173
  • Clients may send the `Content-Length` header, but you cannot rely on that. Can be absent, can be wrong value. Anyway, if you find this header in the request, and it passes the limit, you can early exit when your API stated this header as mandatory. – PeterMmm Jun 25 '22 at 19:06
  • There's no value to implement that check because the actual file size may be unknown before upload limit is reached. Headers aren't very safe way to determine it too. Users won't upload any file that exceeds `10MB` anyway so the validation rule works fine. I would implement that check on the client side instead. – WildDev Jun 25 '22 at 21:49
  • @PeterMmm i try add the validation in preHandle method of HandlerInterceptor. Still the validation hits insider preHandle method only after some duration which is the time it takes to upload 10MB. And i could not add that validation inside a doFilter method because i could not read header values from there. Any comments? – Harshana Jun 26 '22 at 05:29
  • Why you cannot read headers in a filter ? https://stackoverflow.com/questions/25247218/servlet-filter-how-to-get-all-the-headers-from-servletrequest – PeterMmm Jun 26 '22 at 07:41
  • @PeterMmm yes i forgot i could cast it and read values. Actually after i put more logs i identified the spring actually does the validation correctly where if the file size is exceed it throws the exception after hitting the filter without the request goes further in to HandlerInterceptor method. Also I noticed the content bytes reads only after filter and in preHandle method of HandlerInterceptor. – Harshana Jun 26 '22 at 13:16
  • The behavior causeds due to akamai CDN which sit in front of service. After exception throws from service, the cdn does not return the response immediately instead it hangs there for some time and return the 400 and some time it return 503 as well if file size is larger. Probably need to check with CDN team on that behavior – Harshana Jun 26 '22 at 13:17

1 Answers1

0

You can make use of Content-Length header attribute. Basically, it is the number of bytes of data in the body of the request or response.

WildDev
  • 2,250
  • 5
  • 35
  • 67