我正在提交带有文本和文件类型输入字段的表单,并使用此代码获取文本数据
但问题是
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process normal fields here.
//Taking all text and doing task
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value: " + item.getString());
} else {
// Process <input type="file"> here.
//And Leaving this at this time
}
}
如果我解析请求并逐一迭代它,然后在 formField 中我用来获取所有文本参数,之后我再次在文件类型条件下使用此代码来上传文件,这样它就不会再次解析
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process normal fields here.
//Leaving this section this time
} else {
// Process <input type="file"> here.
//Use to Upload file
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value (file name): " + item.getName());
}
}
那么为什么会发生这种情况......以及应该采取什么解决方案......???
最佳答案
HTTP 请求只能被解析一次,因为客户端只发送了一次。 HTTP 请求在第一次解析期间已被全部消耗。在对同一请求进行任何后续解析尝试期间,它不再可用。
如果你想解析它两次,那么客户端基本上必须发送它两次。但是,您不能要求/期望客户这样做,这完全没有意义。只需解析一次,然后为您的具体功能需求寻找不同的解决方案。例如。为两个循环重复使用相同的 items
列表。
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process normal fields here.
}
}
for (FileItem item : items) {
if (!item.isFormField()) {
// Process file fields here.
}
}
请注意,这基本上是低效的代码。因此,我会重新考虑您的功能需求。
关于java - apache.commons.fileuploads 一次解析后未解析请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14978843/