0

我的 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();
        }
    }
}

在这里,我试图将getString()值分配给String数组。在上面的代码中,System.out.printlnWhile循环内部打印值,但在System.out.println外部打印NULL。任何原因,有人可以为我提供解决方案。谢谢您的帮助。

4

1 回答 1

1

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++;
}
于 2013-09-06T04:43:47.490 回答