-2

I'm trying to add uploading zip files to my Spring REST API but I keep getting an error of not being able to consume application/zip

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/zip' not supported

Here is my function in my controller,

@RequestMapping(value = "/zip", method = RequestMethod.POST, consumes = "application/zip")
public ResponseEntity<String> uploadZip(@RequestBody InputStream inputStream) {
    try {
        uploadZip(inputStream)
        return new ResponseEntity<String>(HttpStatus.CREATED);
    } catch (IOException e) {
        logger.warn("Error reading file", e);
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    } catch (Exception e) {
        logger.error("Error creating new job", e);
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

What is causing this exception?

Hank
  • 3,367
  • 10
  • 48
  • 86

1 Answers1

1

Given the @RequestBody annotation, Spring MVC will use a RequestResponseBodyMethodProcessor to resolve an argument for invoking your method. This HandlerMethodArgumentResolver will attempt to find an HttpMessageConverter which can parse application/zip body content and produce an instance of some subtype of InputStream.

There is no such built-in HttpMessageConverter implementation. You can write your own implementation and register it. The Spring MVC stack would pick it up and use it.

Alternatively, if you want just the raw body of the request as an InputStream, just remove the @RequestBody annotation. InputStream is one of the default supported argument types:

java.io.InputStream / java.io.Reader for access to the request’s content. This value is the raw InputStream/Reader as exposed by the Servlet API.

Given the raw InputStream, you could wrap it in a ZipInputStream and do the unzipping yourself.

Another option is to write and register your own implementation of a HandlerMethodArgumentResolver (that looks at a parameter annotation or the actual type of the parameter) that unzips the content of the request into some object.


My answer here explains Spring MVC's HandlerMethodArgumentResolver pattern in more detail.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724