4

I need to receive a csv file on the request and process it.

@PostMapping(value = "/csv", consumes = "text/csv")
  public ViewObject postCsv(@RequestBody InputStream request){
// do stuff
}

But when I execute:

curl -X POST -H 'Content-Type: text/csv' -d @input.csv http://localhost:8080/csv

This is what shows up on my console:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/csv;charset=UTF-8' not supported]

Spring is saying my request is invalid before anything else.

So, the question is: How to properly receive this csv?

kiosia
  • 43
  • 6
  • I believe it should be `@PostMapping(... consumes="text/csv")` _without the trailing semicolon_. But it's been years since I worked with Spring so I'm not sure enough to post an answer. – Jim Garrison Mar 20 '19 at 03:12
  • darn! that was a typo on the question! sorry about that – kiosia Mar 20 '19 at 03:31
  • `@RequestBody` requires an `HttpMessageConverter` for converting the content in the incoming request body to the target data type. Spring Boot does not have an in-built `HttpMessageConverter` for CSV content, therefore does not know how to convert the incoming request body, and hence the exception. A custom `HttpMessageConverter` will have to be written and configured to support CSV content. See [this](https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/csv-msg-converter.html) as an example. – manish Mar 20 '19 at 05:34
  • For a list of media types supported out-of-the-box, see `org.springframework.http.MediaType`. – manish Mar 20 '19 at 05:36
  • @kiosia For future reference ALWAYS copy/paste code, NEVER retype into your question. – Jim Garrison Mar 20 '19 at 07:03

1 Answers1

1

As someone mentioned in comments, one approach is to implement your own HttpMessageConverter - there are examples of varying quality available on the web.

Another option if you already have some code for parsing CSVs using Spring's org.springframework.core.io.Resource classes is to change your method signature as follows to use Spring's built in ResourceHttpMessageConverter:

@PostMapping(path = "/csv", consumes = "application/octet-stream")
    public ViewObject postCsv(@RequestBody Resource resource){
    // do stuff
}
Dave
  • 607
  • 5
  • 16