java - apache.commons.fileuploads 一次解析后未解析请求

标签 java servlets file-upload apache-commons multipartform-data

我正在提交带有文本和文件类型输入字段的表单,并使用此代码获取文本数据

但问题是

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/

相关文章:

java - java中自定义异常中的父类(super class)构造函数

java - OAuth问题,缺少参数access_token

java - 如何将数组与多态性一起使用?

java - 在 Eclipse/Tomcat 上启动 Servlet 打开错误的 URL

php - Symfony fatal error __construct() 必须是 MyBundle\FileUploader 的实例

excel - Odoo 13考勤模块如何设置内部用户上传和导入excel文件的权限?

php - 将 php 文件(当前正在使用)上传到服务器时会发生什么?

java - 托管使用Java和Rails代码的Web应用程序?

java - HttpServletRequest 类型未定义方法 getDispatcherType()

java - 列表迭代 - 用户选择传递给 servlet 的值