处理文件上载时的java.lang.NullPointerException

时间:2012-02-17 08:44:34

标签: java html jsp servlets file-upload

如果您能找到我的问题在哪里以及如何解决问题,我将非常感激。 (显示java.lang.NullPointerException)

这是我从我获取文本字段的html,我上传了2个文件

的index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Insert title here</title>
    </head>
    <body>
    <h3>File Upload:</h3>
    <form action="UploadServlet" method="post"
                            enctype="multipart/form-data">
    <br><br><br><br><br>
    Insert your ID (marca) - ex: 101358 
    <br>
    <input type="text" name="rid" size="40" />
    <br><br>
    Browse your files:
    <br>
    <input type="file" name="file" size="30" />
    <br />
    <br/>
    <input type="file" name="file" size="30" />
    <br />
    <br>
    <input type="submit" value="Upload File" />
    </form>
    </body>
    </html>

在这个servlet中我将上传的文件保存到一个特定的文件夹中,之后我连接到一个数据库,我想存储从html获取的字符串和上传文件中的文件路径

UploadServlet.java

public class UploadServlet extends HttpServlet {

  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  private boolean isMultipart;
  private String filePath;
  private int maxFileSize = 50 * 1024;
  private int maxMemSize = 4 * 1024;
  private File file ;

  public void init( ){
    // Get the file location where it would be stored.
    filePath = getServletContext().getInitParameter("file-upload"); 
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter( );
    if( !isMultipart ){
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
      return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax( maxFileSize );

    try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      //while ( i.hasNext () ) 
      //{
      FileItem fi = (FileItem)i.next();
      if ( !fi.isFormField () )  
        {
          // Get the uploaded file parameters
          //String fieldName = fi.getFieldName();
          String fileName = fi.getName();
          //String contentType = fi.getContentType();
          //boolean isInMemory = fi.isInMemory();
          //long sizeInBytes = fi.getSize();
          // Write the file
          if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File( "C:/UploadedFiles/" + fileName.substring( fileName.lastIndexOf("\\"))) ;
          }else{
            file = new File( "C:/UploadedFiles/" + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
          }
          fi.write( file ) ;
          out.println("Uploaded Filename: " + fileName + " --- saved in C:/UploadedFiles/ " + "<br>");
        }

      FileItem fi2 = (FileItem)i.next();
      if ( !fi2.isFormField () ) 
        {
          // Get the uploaded file parameters
          //String fieldName2 = fi2.getFieldName();
          String fileName2 = fi2.getName();
          //String contentType2 = fi2.getContentType();

          //boolean isInMemory = fi2.isInMemory();
          //long sizeInBytes = fi2.getSize();
          // Write the file
          if( fileName2.lastIndexOf("\\") >= 0 ){
            file = new File( "C:/UploadedFiles/" + fileName2.substring( fileName2.lastIndexOf("\\"))) ;
          }else{
            file = new File( "C:/UploadedFiles/" + fileName2.substring(fileName2.lastIndexOf("\\")+1)) ;
          }
          fi2.write( file ) ;
          out.println("Uploaded Filename: " + fileName2 + " --- saved in C:/UploadedFiles/ " + "<br>");       
        }

      //}
      out.println("</body>");
      out.println("</html>");     
      String idmarca = request.getParameter("rid");

      String itemName1 = fi.getName();
      String path1 = new String("C:\\UploadedFiles\\" + itemName1.substring(itemName1.lastIndexOf("\\")));

      String itemName2 = fi2.getName();
      String path2 = new String("C:\\UploadedFiles\\" + itemName2.substring(itemName2.lastIndexOf("\\")));
      Connection con = null;
      PreparedStatement ps; 

      try{      
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);
        String db = "jdbc:odbc:upload";
        con = DriverManager.getConnection(db, "", "");  
        String sql = "INSERT INTO file1(marca,file1,file2) VALUES(?, ?, ?)";            
        ps = con.prepareStatement(sql);              

        ps.setString(1, idmarca);
        ps.setString(2, path1);
        ps.setString(3, path2);
        int s = ps.executeUpdate();
        if(s>0){
          System.out.println("Uploaded successfully !");
        }
        else{
          System.out.println("Error!");
        }

      }
      catch(Exception e){
        e.printStackTrace();
      }
      finally {
        // close all the connections.
        //ps.close();
        //con.close();
      }
    }catch(Exception ex) {
      ex.printStackTrace();
    }  
  }   


  public void doGet(HttpServletRequest request, 
                    HttpServletResponse response)
    throws ServletException, java.io.IOException {

    throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required.");
  } 
}

java.lang.NullPointerException
    at UploadServlet.doPost(UploadServlet.java:126)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

1 个答案:

答案 0 :(得分:2)

  

好的,我的问题在于字符串idmarca = request.getParameter(&#34; rid&#34;);它从html文本字段中获取文本。在添加此文本字段之前,我能够保存上传文件的文件路径。

使用multipart/form-data请求时,request.getParameter()的表单数据文件可用作请求参数。它们仅作为request.getPart()的表单数据部分提供。但是当您使用Apache Commons FileUpload时(也许您还没有使用新的Servlet 3.0版本,其中getPart()方法可用),那么您实际应该使用相同的API来检索文本字段值。

继续迭代fileItems。文本字段值在那里。

另见: