java.lang.NullPointerException:未设置FileItemFactory

时间:2012-02-21 16:26:18

标签: java gwt servlets

我尝试实现fileUpload,但是我收到了下面描述的错误。

我查了this document,但我没有理解我的代码中存在的问题; 问题出在我在代码中标记的第46行。

有人Plz帮我解决问题。

     private static final String UPLOAD_DIRECTORY = "d:\\";
     public void doPost(HttpServletRequest request,HttpServletResponse response){
         ServletFileUpload upload = new ServletFileUpload();

    if(ServletFileUpload.isMultipartContent(request)){


        FileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        try {
Line 46---> error      List<FileItem> items = upload.parseRequest(request);

             for(FileItem item : items){

                  if( item.isFormField())continue;

                  String fileName = item.getName();
                  if (fileName != null) {
                      fileName = FilenameUtils.getName(fileName);
                                          }
                  File uploadedFile = new File(UPLOAD_DIRECTORY, fileName);
                  if (uploadedFile.createNewFile()) {
                      item.write(uploadedFile);
                      response.setStatus(HttpServletResponse.SC_CREATED);
                      response.getWriter().print("The file was created successfully.");
                      response.flushBuffer();
                  }else{
                      throw new IOException("The file already exists in repository.");
                  }

             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();


        } 
    }else{
        try {
            response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,"Request contents type is not supported by the servlet" );
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

     }

生成错误:

   java.lang.NullPointerException: No FileItemFactory has been set.
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:354)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
    at com.server.FileUpload.doPost(FileUpload.java:46)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

1 个答案:

答案 0 :(得分:3)

guess ,这是因为您使用的upload未使用DiskFileItemFactory进行初始化,而是servletFileUpload,而不是{{1}}。