1

In my JSP I have a form where the user can upload a file.

<form method="post" action="linkToAction" role="form" enctype="multipart/form-data">
  <input name="files" type="file" class="form-control-file" multiple="true" >
</form>

Reading this answer, in my servlet I get the files uploaded:

List<Part> fileParts = request.getParts().stream().filter(part -> "files".equals(part.getName())).collect(Collectors.toList());

If the user doesn't upload anything, I would expect that the List<Part> fileParts would be empty! However, it is not as the above statement adds in the list fileParts, an empty Part. If the user uploads 1 file, the above statement adds again 1 valid Part object.

One quick solution that I thought, is to check the length of the filename:

for (Part filePart : fileParts) {
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); /
         if (fileName.length() != 0) {
                   //do my job here
         }
}

However, why is this happening?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
yaylitzis
  • 5,354
  • 17
  • 62
  • 107

2 Answers2

1

you can check the empty condition in stream itself.

List<Part> fileParts = request.getParts().stream()
                                         .filter(part -> "files".equals(part.getName()) && Objects.nonNull(part.getName()))
                                         .collect(Collectors.toList());
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
1

You need to check if Part#getSize() is bigger than 0.

List<Part> nonEmptyFileParts = request.getParts().stream()
    .filter(part -> "files".equals(part.getName()) && part.getSize() > 0)
    .collect(Collectors.toList());

The referenced answer has in the meanwhile been updated, thanks.

yaylitzis
  • 5,354
  • 17
  • 62
  • 107
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • do you know why this would happen? I ran into something similar. But in my case I receive the filename in part, but part.getSize() is zero. – Mudasir Ali Jun 30 '20 at 08:54
  • @MudasirAli: Most probably bug in specific browser related to autofill or unselecting files. – BalusC Jun 30 '20 at 08:59