Prompted by Janne's download servlet, here's an example of a servlet to load a file to the server. (I use it with a couple of JSP pages. YMMV.)
(This code is still being refined - notice especially that you need to implement authentication and an incoming content handler.)

-- ebu

Also, the free COS package from O'Reilly does this pretty easily. It does the obvious things easily, and is flexible enough to do strange things :).

-- MahlenMorris

COS is usable enough, but its license may not suit all needs. Jason Pell's Multipart Request jar is a small, simple utility under the GPL.

--ebu

Note also that Jakarta now also have their own simple-to-use API for file uploads, the Commons Fileupload project. Unfortunately, it still (09-Dev-2002) has far too much dependencies on other Commons projects that were split off Struts. For example, it requires the Commons Beanutils library, which in turn requires the entire Jakarta Logging package, which obviously is different from log4j, so you end up with hundreds of K of code which you don't mostly use at all.

-- JanneJalkanen.


package net.memecry.traveller;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;


/**
   Simple servlet for receiving a file and launching
   a command, specified in settings, to run it.
 */
public class ReceptorServlet 
    extends HttpServlet
{
    // Index of the one-time key code.
    private static int m_ix = 0;
    // Initialize a key set somehow:
    private String[] m_keys = { "fee", "fie", "foe", "foo" };

    public void init()
    {
        // read application init info
        String storageDir  = getInitParameter(INIT_STORAGE);
        // ...and so on.
        // In reality, you'd load authentication settings here, too.
    }


    public void doGet(HttpServletRequest  req,
                      HttpServletResponse res) 
        throws IOException, ServletException 
    {
        doPost(req, res);
    }


    public void doPost(HttpServletRequest  req,
                       HttpServletResponse res) 
        throws IOException, ServletException 
    {
        ServletContext ctx = getServletContext();
        RequestDispatcher rd = null;
        String msg = null;
        try
        {
            StreamDataSource sds = new StreamDataSource(req);
            MimeMultipart multi = new MimeMultipart(sds);
            // Check that an authentication key exists and is valid. We expect the key to
            // be the first part of the MultiPart, the second the content.
            // (This is pretty inflexible, tune it a bit...)
            MimeBodyPart key = (MimeBodyPart)multi.getBodyPart(0);

            MimeBodyPart content = (MimeBodyPart)multi.getBodyPart(1);
            validateCode((String)(key.getContent())); // throws exception if failed
            handleIncomingFile(content);
            rd = ctx.getRequestDispatcher(successURLString);
            msg = "The content has been handled and stored.";
        }
        catch(MessagingException e)
        {
            // We arrive here e.g. if the input was not a MultiPart.
            // That's fine; add some output and show the submit page.
            msg = "Welcome to the Traveller " +
                  "interface. Use the form to input content.";
            // Maybe add some information to the context:
            req.setAttribute(ATTR_CODEIX, "index: " + m_ix);
            rd = ctx.getRequestDispatcher(submitURLString);
        }
        catch(Exception e)
        {
            // Show the submit page again, but with a bit more 
            // intimidating output.
            msg = "Traveller failure: " + e.getMessage();
            req.setAttribute(ATTR_CODEIX, "index: " + m_ix);
            rd = ctx.getRequestDispatcher(submitURLString);
        }
        
        // add some messages to the request...
        if(msg != null)
            req.setAttribute(ATTR_MSG, msg);

        // ...and forward it to the correct result page.
        if(rd != null)
            rd.forward(req, res);
    }


    private void handleIncomingFile(MimeBodyPart content)
        throws MessagingException
    {
         // Implement your nice dynamic handling code here
    }



    /**
       Trivial one-time key authentication example.
       Compares the offered code string to the currently expected
       passkey. Throws an IllegalAccessException if it is not valid.
       The message contains information on the next key to send.
    */
    private void validateCode(String code)
        throws IllegalAccessException,
               MessagingException
    {
        if(m_ix >= m_keys.length)
            m_ix = 0;
        if(m_keys[m_ix].equals(code))
            m_ix++;
        else
            throw new IllegalAccessException("Next code index is " + m_ix + ".");
    }


  /**
   * This class maps the request stream to the content parser that is
   * able to pick files from it.
   */
  private class StreamDataSource implements DataSource 
  {
      private HttpServletRequest m_req;
      public StreamDataSource(HttpServletRequest req)
      {
          m_req = req;
      }

    /**
     * Returns the content type for the request stream.
     */
    public String getContentType() 
      {
          return m_req.getContentType();
      }

    /**
     * Returns a stream from the request.
     */
    public InputStream getInputStream() 
        throws IOException 
      {
          return m_req.getInputStream();
      }

    /** 
     * This method is useless and it always returns a null.
     */
      public String getName() 
      {
          return null;
      }
    /**
        Maps output to System.out. Do something more sensible here...
     */
      public OutputStream getOutputStream() 
      {
          return System.out;
      }
      
  }
}


To use the above, you need an HTML (well... I'm using JSP) page with something like this:
<FORM ACTION="load" METHOD="POST" ENCTYPE="multipart/form-data">

Enter your key (<%= key %>):
<P>
<INPUT TYPE="text" name="<%= ReceptorServlet.PARAM_KEYCODE%>">
<P>
Upload your content:
<P>
 <INPUT type="file" name="content">
 <P>
 <INPUT type="submit" name="enter" value="Ok">
</form>

Add new attachment

Only authorized users are allowed to upload new attachments.

List of attachments

Kind Attachment Name Size Version Date Modified Author Change note
java
CouponDAO.java 1.0 kB 2 25-Aug-2011 08:38 122.174.94.204 dfgfd
« This page (revision-12) was last changed on 21-Aug-2008 19:14 by JanneJalkanen