Skip to content

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

Closed

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

Activity

  1. spring-projects-issues commented on Sep 20, 2017

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    Like #20472, this turns out to be a general limitation in the conversion infrastructure. The eventual fix for both issues was to make ObjectToOptionalConverter aware of array and collection sources, with special emptiness handling built in.

  2. added
    type: bug
    status: backported
    in: web
    on Jan 11, 2019
  3. added this to the 5.0 GA milestone on Jan 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: webstatus: backportedtype: bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions