当前位置 : 主页 > 编程语言 > java >

jsp – 使用ServletFileUpload的parseRequest上传文件?

来源:互联网 收集:自由互联 发布时间:2021-06-25
参见英文答案 How to upload files to server using JSP/Servlet?12个 我在我的网络应用程序中上传了我使用input type =“file”浏览的文件.问题是我将FileItem列表大小设置为0虽然我可以看到所有上传的
参见英文答案 > How to upload files to server using JSP/Servlet?                                    12个
我在我的网络应用程序中上传了我使用input type =“file”浏览的文件.问题是我将FileItem列表大小设置为0虽然我可以看到所有上传的文件信息

请求 – > JakartaMutltiPartRequest – > files属性

这是读取文件的java代码

public InputStream parseRequestStreamWithApache(HttpServletRequest request)
  throws FileUploadException, IOException {
  InputStream is = null;
  FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  List items = upload.parseRequest(request);
  // here the item size is 0 ,i am not sure why i am not getting my file upload in browser with type="file"
  // but If inspect request in debugger i can see my file realted info in request--->JakartaMutltiPartRequest----->files attribute
  Iterator iter = items.iterator();
  while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (!item.isFormField()) {
      is = item.getInputStream();
    }
  }

  return is;
}

编辑:

这是JSP部分:

<form NAME="form1" action="customer/customerManager!parseRequestStreamWithApache.action" ENCTYPE="multipart/form-data"   method="post" >
     <TABLE >
         <tr>
              <th>Upload File</th>
                  <td>
                   <input name="fileUploadAttr" id="filePath"  type="file" value="">
                 </td>
                  <td > 
                 <Input type="submit" value ="uploadFile"/>
                  </td>
          </tr>
    </TABLE>
</form>
正如我在前面发布的同一个问题的评论中所说,这很可能是因为您之前已经解析过该请求.
这些文件是请求正文的一部分,您只能解析一次.

更新:

我通常以这种方式使用commons-upload:

if (ServletFileUpload.isMultipartContent(request)) {
    ServletFileUpload fileUpload = new ServletFileUpload();
    FileItemIterator items = fileUpload.getItemIterator(request);
    // iterate items
    while (items.hasNext()) {
        FileItemStream item = items.next();
        if (!item.isFormField()) {
            is = item.openStream();
        }
    }
}
网友评论