Skip to content

only one MultipartFile object populated when using an java.util.Optional MutipartFile array or list @RequestParam [SPR-15919] #20473

Closed
@spring-projects-issues

Description

@spring-projects-issues

Brice Roncace opened SPR-15919 and commented

Having the multipart/form-data form:

<form action="<c:url value="/optionalPost"/>" method="post" enctype="multipart/form-data">
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
  <input type="file" name="files" multiple/>
  <input type="submit"/>
</form>

When selecting multiple files for the file input, only one file is actually received by the controller when handling this request:

 // Does NOT work for multiple files (only one comes in)
@PostMapping("/optionalPost")
public String postTest2(@RequestParam Optional<List<MultipartFile>> files) {
  if (files != null && files.isPresent()) {
    System.out.println(files.get().size());
    files.get().forEach(file -> System.out.println(file.getOriginalFilename()));
  }
  return "index";
}

This fails in the same way:

// Does NOT work for multiple files (only one comes in)
@PostMapping("/optionalPost")
public String postTest3(@RequestParam Optional<MultipartFile[]> files) {
  if (files != null && files.isPresent()) {
    System.out.println(files.get().length);
    Stream.of(files.get()).forEach(file -> System.out.println(file.getOriginalFilename()));
  }
  return "index";
}

The workaround is to avoid the use of Optional:

// Works for multiple files
@PostMapping("/optionalPost")
public String postTest4(@RequestParam MultipartFile[] files) {
  System.out.println(files.length);
  Stream.of(files).forEach(file -> System.out.println(file.getOriginalFilename()));
  return "index";
}
// Works for multiple files
@PostMapping("/optionalPost")
public String postTest5(@RequestParam List<MultipartFile> files) {
  System.out.println(files.size());
  files.forEach(file -> System.out.println(file.getOriginalFilename()));
  return "index";
}

Affects: 4.3.10

Issue Links:

Referenced from: commits 53a9697, 15c82af

Backported to: 4.3.12

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions