2013-07-11 439 views
0

我將構建一個簡單的jsp文件來處理使用Servlet的上傳文件。在執行時,它顯示以下消息JSP上傳文件失敗

demo Fail: org.apache.catalina.connector.RequestFacade cannot 

be cast to org.apache.tomcat.util.http.fileupload.RequestContext 

請問如何將HTTP請求轉換爲RequestContext?

下面是我對JSP的頭版

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<!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=ISO-8859-1"> 
<title>Insert title Test Upload</title> 
</head> 
<body> 

<form action="uploadFile" method="post" enctype="multipart/form-data"> 
    <input type="file" name="file" /> 
    <input type="submit" /> 
</form> 

</body> 
</html> 

代碼下面的是我的servlet代碼

import java.io.*; 
import java.net.URL; 
import java.net.URLConnection; 
import java.net.URLEncoder; 
import java.sql.*; 
import java.util.Enumeration; 
import java.util.Iterator; 
import java.util.List; 

import javax.servlet.*; 
import javax.servlet.http.*; 

import org.apache.tomcat.util.http.fileupload.FileItem; 
import org.apache.tomcat.util.http.fileupload.FileItemFactory; 
import org.apache.tomcat.util.http.fileupload.FileUploadException; 
import org.apache.tomcat.util.http.fileupload.RequestContext; 
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; 
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; 

/** 
* Servlet implementation class getLogin 
*/ 
public class uploadFile extends HttpServlet { 

    private static final long serialVersionUID = 17864986468494864L; 


    // location to store file uploaded 
    private static final String UPLOAD_DIRECTORY = "upload"; 

    // upload settings 

    public uploadFile() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    /** 
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
    */ 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
     //doPost(request, response); 
     //throw new ServletException("GET method used with " + getClass().getName()+": POST method required."); 
     request.getRequestDispatcher("/WEB-INF/upload.jsp").forward(request, response); 
    } 

    /** 
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
    */ 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     System.out.println("demo"); 

     if (!ServletFileUpload.isMultipartContent(request)) { 
      // if not, we stop here 
      PrintWriter writer = response.getWriter(); 
      writer.println("Error: Form must has enctype=multipart/form-data."); 
      writer.flush(); 
      return; 
     } 

     // configures upload settings 
     DiskFileItemFactory factory = new DiskFileItemFactory(); 
     // sets temporary location to store files 
     factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); 

     ServletFileUpload upload = new ServletFileUpload(factory); 


     // constructs the directory path to store upload file 
     // this path is relative to application's directory 
     String uploadPath = getServletContext().getRealPath("")+ File.separator + UPLOAD_DIRECTORY; 

     // creates the directory if it does not exist 
     File uploadDir = new File(uploadPath); 
     if (!uploadDir.exists()) { 
      uploadDir.mkdir(); 
     } 

     try { 
      // parses the request's content to extract file data 

      System.out.println(uploadPath); 
      List<FileItem> formItems = upload.parseRequest((RequestContext)request); 
      if (formItems != null && formItems.size() > 0) { 
       // iterates over form's fields 
       for (FileItem item : formItems) { 
        // processes only fields that are not form fields 
        if (!item.isFormField()) { 
         String fileName = new File(item.getName()).getName(); 
         String filePath = uploadPath + File.separator + fileName; 
         File storeFile = new File(filePath); 
         // C:\tomcat\apache-tomcat-7.0.40\webapps\data\ 
         // saves the file on disk 
         item.write(storeFile); 
         request.setAttribute("message","Upload has been done successfully!"); 
         System.out.println("demo Success"); 
        } 
       } 
      } 
     } catch (Exception ex) { 
      request.setAttribute("message","There was an error: " + ex.getMessage()); 
      System.out.println("demo Fail: " + ex.getMessage()); 
     } 
    } 


} 
+0

您可以在BalusC的博客條目中找到解決方案:http://balusc.blogspot.com/2009/12/uploading-files-with-jsf-20-and-servlet.html。搜索'ClassCastException'(在我的答案中重定向您的評論)。 –

+0

仍然無法更改... –

回答

1

在Tomcat 7和Servlet 3.0此錯誤學嘗試,當你得到的參數從不帶標準的enctype = multipart/form-data的表格

@WebServlet("/yourPattern") 
@MultipartConfig 
public class UploadFile extends HttpServlet { //... 

然後使用Part ob JECT作爲

Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file"> 
InputStream filecontent = filePart.getInputStream(); 

,而不是

List<FileItem> formItems = upload.parseRequest((RequestContext)request); 
     if (formItems != null && formItems.size() > 0) { 
      // iterates over form's fields 
      for (FileItem item : formItems) { 
       if (!item.isFormField()) { //... 

見這等崗位以獲取更多信息。

2

這是由於導入不正確而發生的。下載這個jar並將它放在WEB-INF/lib文件夾中。在其他人仍在尋找這個(像我一樣)正確的進口如下所列。

import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileItemFactory; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload;