3

How can I control the max file size and/or the max request size when using resteasy to handle a multipart/form-data request ?

My code looks like this:

@POST
@Path("/somerestresource")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response handleForm(@MultipartForm MyForm form) {
    ...
}

With a Servlet I can control stuff with the @MultipartConfig annotation.

So I'm thinking about bypassing resteasy and using @Context to inject a HttpServletRequest and having my servlet configured inside the web.xml but I'm unsure of the side effects.

thomas.g
  • 3,894
  • 3
  • 29
  • 36

2 Answers2

4

With JAX-RS 2.0, you could use a ContainerRequestFilter bound to your upload method using a @NameBinding annotation. In this filter, you would look at the content-length request header and discard the request if the content length exceeds the maximum value you plan to accept (requestContext.abortWith(...))

With JAX-RS 1.1 and RESTEasy, you could probably do the same thing using a PreProcessInterceptor (http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/html/Interceptors.html#PreProcessInterceptors) and follow a logic logic similar to the one described above.

Xavier Coulon
  • 1,580
  • 10
  • 15
  • After days of searching, I guess it's the way to go ! I was looking for more "built-in" solutions but I can't find anything. Thanks ! – thomas.g Jan 17 '14 at 10:48
  • Content-Length is not the right way to get the file size, technically the header is optional, please see the response on the a similar request here https://stackoverflow.com/a/34811675/2517413 – Réda Jan 03 '18 at 09:55
1

In addition to the answer by Xavier, you can also get the content-length header from an injected @Context HttpServletRequest. Furthermore, this is not enough, because the header may not be available (e.g. when chunking is used for the POST body). You then have two options: let the call fail, because you don't know the length of the stream, or resort to using, e.g., BoundedInputStream to read the body of the upload part of the request.

Minor detail: the content-length header is usually sent along with the main request, and not with each part of the multipart data. It therefore does not accurately represent the size of the upload.

scranen
  • 31
  • 1