0

I am currently working on file uploading through servlets and I am getting a 404 error. Here is my code

FileUpload.html

<html>
    <head>
        <title>File Uploading Form</title>
    </head>
    <body>
        <h3>File Upload:</h3>
        Select a file to upload: 
        <br />
        <!-- form tag is genraly used for user input-->
        <!-- action attr defines action to be performed when form is submitted -->
        <!-- method attr defines the HTTP method to be used when submitting forms -->
        <!-- enctype attr specifies the encoding of the submitted data -->
        <form action="UploadServlet" method="post" enctype="multipart/form-data"> 
        <!-- size attr specifies the visible width in chars of an <input> element -->
        <input type="file" name="file" size="50" />
        <br />
        <input type="submit" value="Upload File" />
        </form>
    </body>
</html>

I have updated my web.xml file also as follows

<context-param> 
    <description>Location to store uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>c:\apache-tomcat-5.5.29\webapps\data\</param-value> 
</context-param>
<servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

UploadServlet.java // Import required java libraries

import java.io.*;
import java.util.*;
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 UploadServlet extends HttpServlet {
    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 = 
         getServletConfig().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");
     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.");
 } 
}
singhakash
  • 7,891
  • 6
  • 31
  • 65
Srividya
  • 119
  • 1
  • 1
  • 9

3 Answers3

0

You need to provide contextPath to properly refer to Servlet URL, I mean your action attribute of your form must be <form action="/AppContext/UploadServlet" ...

If you are using JSP or whatever, instead plain HTML, you could use some scriptlet or jstl to retrieve context path programatically, for example:

<form action="<%=request.getContextPath()%>/UploadServlet" ...

or

<form action="${pageContext.request.contextPath}/UploadServlet" ...

Hope it helps!

malaguna
  • 4,183
  • 1
  • 17
  • 33
0

It might be because of your project structure, Check the below few things once.

 $CATALINA_HOME
 |
 |__webapps
      |
      |___FileUploadProj
              |
              |
              |______WEB-INF
              |         |__classes
              |         |    |__UploadServlet.class
              |         |
              |         |__src
              |         |   |___UploadServlet.java
              |         |
              |         |__lib
              |         |   |___*.jar
              |         |
              |         |__web.xml
              |
              |_____FileUpload.html
              |
              |_____css,images, scripts
  • Keep your java UploadServlet.java under src folder.
  • once you complile the java file copy the UploadServlet.class file and keep it under classes folder. (I doubt this might be issue in your case, don't forget to copy .class file every time you change .java file)
  • Keep web.xml under WEB-INF folder
  • place FileUpload.html outside of WEB-INF

Once you make sure the above things, just give a try.

Uppicharla
  • 494
  • 8
  • 18
0

I tried with the code you provided, when I uploaded one file it returned response as:

Uploaded Filename: image01.jpg

I suspect the way you packaged your application for deployment.What @Uppicharla provided is correct.

I deployed as follows:

webapps\
        TestUpload\
                  index.html

                   WEB-INF\
                           classes\UploadServlet.class
                           lib\commons-fileupload-1.3.jar,commons-io-2.4.jar
                           web.xml

Where TestUpload is my application name, index.html is my upload html. The web.xml I used is :

<?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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>TestUpload</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <context-param>
        <description>Location to store uploaded file</description>
        <param-name>file-upload</param-name>
        <param-value>G:\apache-tomcat-7.0.37\webapps\data\</param-value>
    </context-param>
    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/UploadServlet</url-pattern>
    </servlet-mapping>
</web-app>

Please try with this.

Note: I tried it with tomcat 7 with servlet spec 2.5

One more thing ,you are using tomcat 8 right? but in your web.xml you specified one path of tomcat 5

Tom Sebastian
  • 3,373
  • 5
  • 29
  • 54