3

使用带有 HTML 表单的 servlet 在服务器上上传 txt 文件,但显示以下错误:

    cannot find symbol filePath = getServletContext().getInitParameter("file-upload");  

jar 文件添加:

commons-fileupload-1.3.jar, commons-io-2.4.jar, servlet-api-3.0.jar

使用 NetBeansIDE 和在 web.xml 中设置的参数,路径为“C:\apache-tomcat-7.0.40\webapps\ROOT\WEB-INF”

<context-param> 
    <description>destination storing uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>
     C:\apache-tomcat-7.0.40\webapps\data\
     </param-value> 
</context-param>  

尝试了以下代码:FileUpload3

package fileupload3;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;


public class FileUpload3 {

    private boolean isMultipart;

   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init()  {
      // Showing cannot find symbol getServletContext() error here
      filePath = getServletContext().getInitParameter("file-upload");   

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

      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( filePath + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {

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

HTML 表单:newhtml1.html

<html>
<head>
<title>HTML Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="FileUpload3" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
4

1 回答 1

4

它应该扩展HttpServlet类。替换public class FileUpload3public class FileUpload3 extends HttpServlet,它将起作用。

于 2013-10-22T09:04:04.457 回答