Servlets 为什么Servlet认为我的空HTML文件元素中有一个文件?

Servlets 为什么Servlet认为我的空HTML文件元素中有一个文件?,servlets,file-upload,is-empty,Servlets,File Upload,Is Empty,我使用Java Servlet处理html表单,它包括一个文件输入元素: <input type="file" id="fileUpload" name="file" multiple /> 我使用中的示例代码一次处理多个文件。我使用的代码是: List<Part> fileParts = req.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collecto

我使用Java Servlet处理html表单,它包括一个文件输入元素:

<input type="file" id="fileUpload" name="file" multiple />

我使用中的示例代码一次处理多个文件。我使用的代码是:

List<Part> fileParts = req.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">
for (Part filePart : fileParts) {
            String fileName = filePart.getSubmittedFileName();
            InputStream fileContent = filePart.getInputStream();
            // Do stuff here
}
List fileParts=req.getParts().stream().filter(part->“file”.equals(part.getName()).collect(Collectors.toList());//检索
对于(部分文件部分:文件部分){
字符串文件名=filePart.getSubmittedFileName();
InputStream fileContent=filePart.getInputStream();
//在这里做事
}

这段代码非常有效。我的问题是,当我不附加任何内容时,我的代码仍然认为fileParts中有Part对象。在进行一些调试时,Part对象似乎确实存在,但当然没有要获取的InputStream或SubmittedFileName,因为我没有上载任何文件。为什么会这样?我不熟悉lambda函数和集合,但是当我没有选择任何要上载的文件时,这个“fileParts”集合似乎应该是空的。

这就是HTML的工作方式

非文件输入也是如此。提交空输入时,您会得到一个空值,而不是
null
。差异是显著的。值
null
表示没有输入字段。当表单有多个提交按钮并且您希望按下按钮时,这一点特别有用

给定一个

和一个


检查浏览器网络控制台。它是否将输入提交为空?这仍然有效。
String foo = request.getParameter("foo");

if (foo == null) {
    // foo was not submitted at all.
} else if (foo.isEmpty()) {
    // foo is submitted without value.
} else {
    // foo is submitted with a value.
}
Part bar = request.getPart("bar");

if (bar == null) {
    // bar was not submitted at all.
} else if (bar.getSize() == 0) {
    // bar is submitted without value.
} else {
    // bar is submitted with a value.
}