4

My api receives a param MultipartFile. I am unable to bind that file with a list of objects?

I work on Spring-boot 2.0.8 with Java 8

I tried this:

public ResponseEntity<Long> addReferenceByFile(HttpServletRequest request,
                                               @PathVariable String numeroLicence,                                                     
@RequestParam("references") MultipartFile references) throws URISyntaxException {

and this:

try {
     InputStream inputStream = references.getInputStream();
     ObjectMapper objectMapper = new ObjectMapper();
     ArrayList<Reference> references1 = objectMapper.readValues(references, Reference.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

ObjectMapper doesn't accept InputStream data. My requirement is to get a list to use for unitary treatment.

Would someone help me find a solution for this issue?

vss
  • 1,093
  • 1
  • 20
  • 33
user1450740
  • 731
  • 10
  • 26

2 Answers2

0

You can use InputStreamReader to read the multipart InputStream:

try (InputStream in = references.getInputStream()) {
    objectMapper.readValue(new InputStreamReader(in), Reference.class);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

I found the solution :

ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
    try {
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, Reference.class);
        List<Reference> referenceList = objectMapper.readValue(references.getInputStream(), collectionType);



    } catch (IOException e) {
        throw new CustomException(CustomError.ERROR_REFERENCE_FILE_BAD_FORMAT);
    }
user1450740
  • 731
  • 10
  • 26