【问题标题】:Issues with simple Apache FileUpload API example简单 Apache FileUpload API 示例的问题
【发布时间】:2012-03-31 20:56:35
【问题描述】:

我是 Apache 的 Java FileUpload API 的新手,首先,我找到了一个 tutorial,它解释了如何在 Servlet 中使用 FileUpload。我正在使用 Eclipse 3.7 并创建了 Dynamic 项目来尝试链接中解释的示例。以下是我的项目目录结构。

虽然UploadImage.java 的代码与示例中提到的相同,但我在servlets 包中有servlet 文件并且文件MIME 类型是JPEG 图像而不是纯文本。现在,我是 Eclipse 中 servlet 开发的新手,但根据我的理解,从 servlet 创建的类文件必须保存在 WEB-INF\classes 文件夹中,并且它的条目在 web.xml 中。此外,index.jsp 代码与给定教程示例中提到的相同。现在,我的index.jsp 中有<form action="/servlets.UploadImage" enctype="multipart/form-data" method="post">。 当我尝试运行该项目时,index.jsp 看起来很有趣,但是当我选择图像文件并点击上传时,我最终得到了404 not found 错误。另外,如何让Eclipse在我构建项目时将UploadImage.java生成的类文件放在WEb-INF\classes中。

过去 4 小时我一直在努力运行这个简单的示例,并且是 Eclipse 中 servlet 开发的新手,我对如何使用它一无所知,因此感谢任何帮助。

注意:所有必需的 .jar 文件都包含在项目库中。

更新:按照BalusC 的建议进行更改后,我仍然无法解决问题。我提供了项目的 3 个重要文件的确切代码,我认为这与该问题有关。项目的目录结构还是如上所示。

  • index.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Image Upload Example</title>
    <style type="text/css">
        #uploadimage {
            width: 150px;
            height: 150px;
            background: #f8f8f8;
        }
    </style>
    </head>
    <body>
    <div id="uploadimage">&nbsp;</div>
    <form action="servlets.UploadImage" enctype="multipart/form-data" method="post">
        <input type="file" name="file1"><br/>
        <input type="submit" value="Upload File"><br/>
    </form>
    </body>
    </html>
    
  • UploadImage.java (servlet)

    package servlets;
    
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.annotation.*;
    import javax.servlet.http.*;
    
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    /**
     * Servlet implementation class UploadImage
     */
    @WebServlet("/UploadImage")
    public class UploadImage extends HttpServlet
    {
    
       private static final long serialVersionUID = 1L;
       private static final String temppath = System.getenv("temp");
       private File tempdir;
       private static final String storepath = "/Uploads";
       private File storedir;
    
       public void init(ServletConfig config) throws ServletException
       {
          super.init(config);
    
          tempdir = new File(temppath);
          if (!tempdir.isDirectory())
          {
             throw new ServletException(temppath + " is not a directory.");
          }
    
          String realpath = getServletContext().getRealPath(storepath);
    
          storedir = new File(realpath);
          if (!storedir.isDirectory())
          {
             throw new ServletException(storepath + " is not a directory.");
          }
       }
    
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
       {
          PrintWriter out = response.getWriter();
          response.setContentType("image/jpeg");
          out.println("<h2 align='center'>Impage Upload Example</h2>");
    
          DiskFileItemFactory fif = new DiskFileItemFactory();
          fif.setSizeThreshold(5 * 1024 * 1024);
          fif.setRepository(tempdir);
    
          ServletFileUpload uh = new ServletFileUpload(fif);
          try
          {
             List items = uh.parseRequest(request);
             Iterator itr = items.iterator();
             while (itr.hasNext())
             {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField())
                {
                   out.println("File Name = " + item.getFieldName() + ", Value = " +                        item.getString());
                }
                else
                {
                   out.println("Field Name = " + item.getFieldName()
                        + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType()
                        + ", File Size = " + item.getSize());
                   File file = new File(storedir, item.getName());
                   item.write(file);
                }
                out.close();
            }
        }
        catch (FileUploadException fex)
        {
           out.println("Error encountered while parsing the request<br/>" + fex);
        }
        catch (Exception ex)
        {
           out.println("Error encountered while parsing the request<br/>" + ex);
        }
      }
    }
    
  • web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>Apache FileUpload</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>UploadImage</servlet-name>
        <servlet-class>servlets.UploadImage</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>UploadImage</servlet-name>
        <url-pattern>/servlets.UploadImage</url-pattern>
      </servlet-mapping>
    </web-app>
    

抱歉问了这么长的问题。 :-P

【问题讨论】:

    标签: eclipse jsp tomcat servlets file-upload


    【解决方案1】:
    <form action="/servlets.UploadImage" ...>
    

    您的表单操作 URL 以 / 开头,因此相对于域根。想象一下,您的 JSP 文件是由

    打开的

    http://localhost:8080/contextname/index.jsp

    那么这个相对表单动作 URL 会将 POST 请求发送到下面的绝对 URL

    http://localhost:8080/servlets.UploadImage

    其实应该是这样的

    http://localhost:8080/contextname/servlets.UploadImage

    所以,去掉前面的斜线。

    <form action="servlets.UploadImage" ...>
    

    关于您的其他问题:

    另外,如何让Eclipse在我构建项目的时候,把生成的UploadImage.java类文件放到WEB-INF\classes中。

    它已经自动完成了。好吧,准确地说是WEB-INF/classes,而不是WEb-INF/classes。 Java 区分大小写。

    也就是说,您的 URL 模式很奇怪。为什么不只是/upload

    另见:

    【讨论】:

    • WEb-INF/classes 在我的问题中只是一个错字:-) 但是,我将表单的操作更改为 servlets.UploadImage (删除正斜杠),但我仍然得到相同的 404 not found 错误。我正在更新问题以反映我创建的index.jspUploadImage.java servlet 的代码。此外,servlet 的类文件没有在我的 web 应用程序的 WEB-INF\classes 中创建。
    • 在servlet初始化过程中,如果没有任何异常,您是否阅读过webapp的启动日志?此外,我注意到您已经以两种方式注册了 servlet。一个带有新的 @WebServlet 注释,另一个带有 oldschool web.xml 条目。 web.xml 注册将获得优先权,但 @WebServlet 注册将在 /UploadServlet 的 URL 模式上注册,这与您的 web.xml 注册不同。您是否了解您实际在做什么?
    • 好的,@WebServletweb.xml 注册冲突,我应该保留什么?鉴于我在任何一种使用的注册方法中将 url-pattern 修改为 servlets.UploadImage。我现在所做的是删除@WebServlet并保留web.xml注册,第一次运行webapp会抛出ClassNotFoundException,如果我重新运行,我再次陷入404错误。
    【解决方案2】:

    UploadImage.java 的第一行是什么? 如果是

    package servlets; 
    

    然后代替使用

    <servlet-class>UploadImage</servlet-class> 
    

    使用

    <servlet-class>servlets.UploadImage</servlet-class>  
    

    UploadImage.class 文件应位于 WEB-INF/classes/servlets 文件夹中。 而不是使用

     <url-pattern>/servlets.UploadImage</url-pattern>  
    

    使用类似的东西

    <url-pattern>/up</url-pattern>   
    

    并浏览到

    <yourHost>/<yourWebAppName>/up
    

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2012-11-10
      • 2011-05-21
      相关资源
      最近更新 更多