为什么 Servlet 认为我的空 HTML 文件元素中有一个文件?
Why does Servlet think my empty HTML file element has a file in it?
我正在使用 Java Servlet 来处理 html 表单,它包含一个文件输入元素:
<input type="file" id="fileUpload" name="file" multiple />
我使用 this excellent answer 中的示例代码一次处理多个文件。我使用的代码是:
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
}
这段代码效果很好。我的问题是,当我不附加任何东西时,我的代码仍然认为 fileParts 中有一个 Part 对象。进行一些调试后,Part 对象似乎确实存在,但当然没有 InputStream 或 SubmittedFileName 可获取,因为我没有上传任何文件。为什么是这样?我是 lambda 函数和集合的新手,但是当我没有 select 任何要上传的文件时,这个 "fileParts" 集合似乎应该是空的。
这就是 HTML 的工作原理。
非文件输入也是如此。提交空输入时,您会得到一个空值,而不是 null
。差异很大。值 null
表示没有输入字段。当表单有多个提交按钮并且您想 distinguish 按下按钮时,这特别有用。
给定 <input type="text" name="foo">
,
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.
}
还有一个<input type="file" name="bar">
,
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.
}
我正在使用 Java Servlet 来处理 html 表单,它包含一个文件输入元素:
<input type="file" id="fileUpload" name="file" multiple />
我使用 this excellent answer 中的示例代码一次处理多个文件。我使用的代码是:
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
}
这段代码效果很好。我的问题是,当我不附加任何东西时,我的代码仍然认为 fileParts 中有一个 Part 对象。进行一些调试后,Part 对象似乎确实存在,但当然没有 InputStream 或 SubmittedFileName 可获取,因为我没有上传任何文件。为什么是这样?我是 lambda 函数和集合的新手,但是当我没有 select 任何要上传的文件时,这个 "fileParts" 集合似乎应该是空的。
这就是 HTML 的工作原理。
非文件输入也是如此。提交空输入时,您会得到一个空值,而不是 null
。差异很大。值 null
表示没有输入字段。当表单有多个提交按钮并且您想 distinguish 按下按钮时,这特别有用。
给定 <input type="text" name="foo">
,
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.
}
还有一个<input type="file" name="bar">
,
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.
}