0

I'm new to Java FileUpload APIs of Apache, and for a start, I found a tutorial that explains how FileUpload can be used in a Servlet. I'm using Eclipse 3.7 and created Dynamic project to try the example explained in the link. Following is my project directory structure.

Project Directory Structure

While the code of UploadImage.java is same as mentioned in the example, except that I have the servlet file in servlets package and file MIME type is JPEG image instead of plain text. Now, I'm new to servlet development in Eclipse, but as per my understanding, the class file created from the servlet must be kept within WEB-INF\classes folder, and its entries in the web.xml. Also, the index.jsp code is same as mentioned in the example of given tutorial. Now, I have <form action="/servlets.UploadImage" enctype="multipart/form-data" method="post"> in my index.jsp. When I try to run the project, index.jsp appears just fun but when I select image file and hit upload, I end up with 404 not found error. Also, how can I make Eclipse put generated class file of UploadImage.java in WEb-INF\classes when I build the project.

I've been working to run this simple example for last 4 hours and being new to servlet development in Eclipse, I'm clueless about how to work with this, so any help is appreciated.

Note: All required .jar files are included in the project libraries.

Update: After making changes as suggested by BalusC, I still can't get the problem soved. I'm providing the exact code of 3 important files of the project which I believe has something to do with the issue. Directory structure of the project is still the same as shown above.

  • 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>
    

Sorry for such a long question. :-P

Community
  • 1
  • 1
Kushal
  • 3,112
  • 10
  • 50
  • 79

2 Answers2

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

Your form action URL starts with / and is thus relative to domain root. Imagine that your JSP file is opened by

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

Then this relative form action URL will send the POST request to the following absolute URL

http://localhost:8080/servlets.UploadImage

while it should really have been

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

So, remove the leading slash.

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

As to your additional question:

Also, how can I make Eclipse put generated class file of UploadImage.java in WEb-INF\classes when I build the project.

That does it already automatically. Well, in WEB-INF/classes to be precise, not in WEb-INF/classes. Java is case sensitive.

That said, you've pretty an odd URL pattern there. Why not just /upload?

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • `WEb-INF/classes` in my question was just a typo :-) However, I changed form's action to `servlets.UploadImage` (removing the forward slash), but I'm still getting same 404 not found error. I'm updating the question to reflect the code of both `index.jsp` and `UploadImage.java` servlet that I've created. Also, the classfile of the servlet is not getting created in `WEB-INF\classes` in my webapp. – Kushal Apr 01 '12 at 09:08
  • Have you read the webapp's startup log if there isn't any exception during servlet's initialization? Further I notice that you've registered the servlet in 2 ways. One with new `@WebServlet` annotation and other with oldschool `web.xml` entry. The `web.xml` registration would get precedence, but the `@WebServlet` registration as you have there registers it on an URL pattern of `/UploadServlet` which is different from your `web.xml` registration. Are you *understanding* what you're actually doing there? – BalusC Apr 01 '12 at 12:48
  • Ok so `@WebServlet` is conflicting with `web.xml` registration, so what shall I keep? given that I modify url-pattern to `servlets.UploadImage` in any one of the used registration methods. What I did for now is removed the `@WebServlet` and kept `web.xml` registration, and running the webapp first time throws `ClassNotFoundException` and if I re-run, I'm again dropped to 404 error. – Kushal Apr 01 '12 at 14:03
0

What is first line of UploadImage.java ? If it is

package servlets; 

then instead of using

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

use

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

The UploadImage.class file should be in the WEB-INF/classes/servlets folder. Instead of using

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

use something like

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

and browse to

<yourHost>/<yourWebAppName>/up
rickz
  • 4,324
  • 2
  • 19
  • 30