0

I'm developing a service that will receive a file through an HTTP Post request. The file is sent by the request body with a Content-Type: application/octet-stream header. I want to limit the request body to 10MB. Here's a MRE of my goal:

@RestController
public class MyController {

    @PostMapping("save")
    public ResponseEntity<Map<String, Object>> save(@RequestBody byte[] data) {
        return ResponseEntity.ok(Map.of("size", data.length));
    }
}

To test my endpoint I tried this curl command:

curl -X POST -H "Content-Type: application/octet-stream" --data-binary "@my_big_binary_file.whatever" http://localhost:8080/save

I tried to set the following properties, but with no success:

server.tomcat.max-http-form-post-size=10MB
server.tomcat.max-swallow-size=10MB

So, my question is: I'm going have multiple requests like this on my service. How can I limit the size of all of them to 10MB? Also, and I think it's related: what's the purpose of these two properties? Isn't it what I was expecting?

Tested using Java 17 on Spring Boot 2.7.9 and 3.0.4


PS.: I know there's a way to limit multipart/form-data requests using the properties below. That works just fine. But it's not what I need.

spring.servlet.multipart.max-file-size=10MB
Marcelo Barros
  • 930
  • 9
  • 16
  • 1
    Does this answer your question? [Limit size of http application/json request body in Spring, tomcat](https://stackoverflow.com/questions/46118627/limit-size-of-http-application-json-request-body-in-spring-tomcat) – Chin Huang Mar 09 '23 at 16:14

1 Answers1

1

Well, the response that Chin Huang inserted is valid! You would need to change it only a little bit to limit octet-stream only.

It would be almost like that:


@Component
public class ApplicationJsonRequestSizeLimitFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
        if (isApplicationOctet(request) && request.getContentLengthLong() > 10000) {
            throw new IOException("Request content exceeded limit of 10000 bytes");
        }
        filterChain.doFilter(request, response);
    }

    private boolean isApplicationOctet(HttpServletRequest httpRequest) {
        return (MediaType.APPLICATION_OCTET_STREAM.isCompatibleWith(MediaType
                .parseMediaType(httpRequest.getHeader(HttpHeaders.CONTENT_TYPE))));
    }
}

This solution is based on Chin Huang answer, just adjusting the datatype.