0

I am trying to create and deploy a simple web-service on Tomcat 7 (locally on my machine). Its a Java Servlet to upload an image to the server, store it locally on some directory and then invoke another function downstream in my Servlet.

While attempting to post the image to the servlet, I run into this error:

HTTP Status 405 - HTTP method POST is not supported by this URL
type Status report
message HTTP method POST is not supported by this URL
description The specified HTTP method is not allowed for the requested resource.

I followed few related posts discussing this same issue but I am unable to narrow down on the issue. Any help would be appreciated.

My source code (with comments):

UploadServlet.java

package com.apps.servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.apps.services.SearchByURL;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.File;
import java.io.OutputStream;

public class UploadServlet extends HttpServlet {
    private String filePath;
    private File file;
    private String bestGuessString;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
        bestGuessString = "";

        filePath = getServletContext().getInitParameter("file-upload");
        System.out.println("filePath: " + filePath);
        filePath = getServletContext().getRealPath(filePath);
        System.out.println("filePath2: " + filePath);

        String fileName = "";
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();
                OutputStream outputStream = null;

                if (item.isFormField()) {
                    System.out.println("Got a form field: "
                            + item.getFieldName());
                } else {
                    System.out.println("Got an uploaded file: "
                            + item.getFieldName() + ", name = "
                            + item.getName());
                    fileName = item.getName();
                    System.out.println("Absolute path: " + filePath + "/"
                            + fileName);

                    outputStream = new FileOutputStream(new File(fileName));
                    int len;
                    byte[] buffer = new byte[8192];
                    while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                        response.getOutputStream().write(buffer, 0, len);
                        outputStream.write(buffer, 0, len);
                    }
                }
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

            //Downstream logic (I am using the image and passing it to another custom class)
            //CustomClass.java is defined separately
        String finalGuess = CustomClass.customFunction(fileName);
        if (finalGuess.equals(""))
            bestGuessString = "Sorry! Google did not find the image interesting enough.. :)";
        else
            bestGuessString = finalGuess;

        //Redirecting the response to doGet and printing the final result there
            response.sendRedirect("/UploadServlet?imageUrl=" + bestGuessString);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
        String imageUrl = request.getParameter("imageUrl");
        response.setHeader("Content-Type", "text/html");
        System.out.println("in doGet(), imageUrl: " + imageUrl);
        response.getWriter().println("Best Guess: " + bestGuessString);
    }

    public void init() {
        // Get the file location where it would be stored.
        filePath = getServletContext().getInitParameter("file-upload");
    }
}

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.apps.servlets.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/UploadServlet</url-pattern>
    </servlet-mapping>
    <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>
             data
         </param-value> 
    </context-param>
</web-app>

index.html

<!doctype html> 
<html>
   <head>
      <title>File Uploading Form</title>
   </head>
   <body>
      <h3>File Upload:</h3>
      Select a file to upload: <br /> 
      <form
         action="UploadServlet" method="post" enctype="multipart/form-data"> <input
         type="file" name="file" size="50" /> <br /> <input type="submit" value="Upload
         File" /> </form>
   </body>
</html>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.apps.innovative</groupId>
    <artifactId>VoyagerServices</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>VoyagerServices Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.0-alpha4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.james</groupId>
            <artifactId>apache-mime4j</artifactId>
            <version>0.6.1</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Maven Tomcat Plugin -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <configuration>
                    <url>http://127.0.0.1:8080/manager/html</url>
                    <server>TomcatServer</server>
                    <path>/VoyagerServices</path>
                    <username>admin</username>
                    <password>password</password>
                </configuration>
            </plugin>
            <!-- Maven compiler plugin -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
G3M
  • 1,003
  • 7
  • 16
  • 1
    Thanks! It doesn't seem to help though. I get this error: HTTP Status 404 - /contextpath/UploadServlet. type Status report message /contextpath/UploadServlet description The requested resource is not available. – G3M Jun 15 '14 at 18:50
  • Did you check this ? http://stackoverflow.com/questions/4297049/http-status-405-http-method-post-is-not-supported-by-this-url-java-servlet – Hardik Mishra Jun 16 '14 at 06:58
  • That means your servlet has no doPost method. Are you sure your url-pattern is mapped to this servlet and not another? – developerwjk Jun 16 '14 at 17:18
  • I have a doPost method and the url patters is mapped to the right servlet – G3M Jun 16 '14 at 18:45

1 Answers1

-2
**html code**

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="upload" enctype="multipart/form-data" >
            File:
            <input type="file" name="file" id="file" /> <br/>
            Destination:
            <input type="text" value="/tmp" name="destination"/>
            </br>
            <input type="submit" value="Upload" name="upload" id="upload" />
        </form>
    </body>
</html>


**servlet code**

package servlet;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER
            = Logger.getLogger(FileUploadServlet.class.getCanonicalName());

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
                response.setContentType("text/html;charset=UTF-8");

        // Create path components to save the file
        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();

        try {
            out = new FileOutputStream(new File(path + File.separator
                    + fileName));
            filecontent = filePart.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            writer.println("New file " + fileName + " created at " + path);
            LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
                    new Object[]{fileName, path});
        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                    + "trying to upload a file to a protected or nonexistent "
                    + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());

            LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
                    new Object[]{fne.getMessage()});
        } finally {
            if (out != null) {
                out.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
     @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


**Also Check this Link**

http://multiplejava.blogspot.in/2015/03/upload-files-to-server-via-java-servlet.html

[ALSO CHECK THIS LINK]