我上传文件,并在我的网络应用程序中使用
input type="file"
浏览该文件。
问题是,我得到的
FileItem
列表大小为0
,尽管我可以在下看到所有上传的文件信息
request -> JakartaMutltiPartRequest -> files attributes
这是读取文件的 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();
}
}
}
您应该检查多部分内容
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
}
}
} catch (Exception e) {
您可以在此处找到此类 servlet 的示例。
您上传的文件有多大?您可能超过了默认阈值。我认为默认是10K
factory.setSizeThreshold(maxSizeYouWantToHandle);
如果您使用的是 weblogic 12,请检查 patch_wls1211 是否已安装。我遇到了同样的问题,应用 patch_wls1211 后解决了。