[英]Apache Commons FileUpload getString() method - Java
My FileUpload Servlet code: 我的FileUpload Servlet代码:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
NewsItems ni = new NewsItems();
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
String [] myValues = new String[6];
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
int i = 0;
if (item.isFormField()) {
myValues[i] = item.getString();
System.out.println("my vals: "+myValues[i]); //PRINTS THE VALUES
}
i++;
}
String newsContent = myValues[2]; //PRINTS NULL
System.out.println(newsContent);
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here I'm trying to assign getString()
values to a String
Array. 在这里,我试图将
getString()
值分配给String
数组。 In above the code , System.out.println
which is inside the While
Loop prints the values but the System.out.println
outside prints NULL
. 在上面的代码中,
While
循环内的System.out.println
打印值,而外面的System.out.println
打印NULL
。 Any reasons for this and can someone please provide me a solution. 任何原因,有人可以为我提供解决方案。 Thanks for the help.
谢谢您的帮助。
Finally found the answer. 终于找到答案了。 I have done a silly mistake by initializing the
i
inside the while loop. 我通过在while循环中初始化
i
犯了一个愚蠢的错误。
int i = 0;
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) {
myValues[i] = item.getString();
System.out.println("my vals: "+myValues[i]); //PRINTS THE VALUES
}
i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.