My FileUpload Servlet code:
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. In above the code , System.out.println
which is inside the While
Loop prints the values but the System.out.println
outside prints 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.
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++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.