How to do Upload File or Attachment in JSP or Servlet


Web tier: servlets, JSP, Web frameworks: How to do Upload File or Attachment in JSP or Servlet

  1. I have facing the problem in developing a servlet program which allow the user to upload or attach the document into the server ...

    Hereby i found in we need to set the HTML to
    <FORM METHOD="Post" NAME="FormName"

    and we can use the File Type to browse the file
    <INPUT VALUE="Browse" TYPE="FILE" NAME="cmdBrowse">

    But in servlet/jsp is there any Java Standard library to use inorder to store the file?

  2. Unfortuantely there is none.. But you can
    search the internet to get the code..
    Java Web Server comes with FileUploadServlet...
    OReily's Servlet Book contains case to handle

    What you need to remember is that you would get
    Mime encoded data and you need to parse it..
  3. once you specified
    <FORM METHOD="Post" NAME="FormName" Action="/UploadServlet"

    <INPUT VALUE="Browse" TYPE="FILE" NAME="cmdBrowse">

    whenthis form to a servlet the file contents will be embedded in the body of the request form data seperated by boundaries.
    your servlet need to locate the boundaries and read the
    file contents from request objects input stream and save it to a file on the servers local file system.

    best regards
  4. Try this link:

    Here's some additional information:

    Wutka's "Using Java Server Pages and Servlets" - p. 233 has an example.

    Also check out the article on Sun's web site:

    The code I actually ended up using was much simpler than Sun's example. I reduced the code to only what I needed and hard-coded some values as well. Using the Multipart class in J2EE may have been a better solution, but I wasn't sure how to use the class properly and hard-coding worked fine for my current situation.

    Note that the request.getParameter("param") function does not work when using multipart form data. Be aware of this if you have additional parameters that you would like to read on the same page that you are using to upload a file.

      // Read the request header line by line until you find the data you're looking for.
      // In my case, I'm looking for an XML tree that begins with "<myXML>" and ends with
      // "</myXML>"
      private String getXMLFromFile(HttpServletRequest request) throws IOException
        BufferedReader br = request.getReader();
        StringBuffer buffer = new StringBuffer(500000);
        String line;

        // Skip the crap in the header

        while ((line = br.readLine()) != null)
          if ( line.startsWith("<myXML") )

        // Read the XML and skip the crap after XML

        while ( line != null )
          if ( line.startsWith("</myXML") )
          line = br.readLine();

        return buffer.toString();