2

I have a Java class that accepts an InputStream and encodes the data coming in. How do I get something working that will accept a file upload from the user, but treat it as a stream without saving the whole thing to disk first and using FileInputStream?

Basically I'm looking for some lightweight web framework in Java that will just let me get a file uploaded by the user as a data stream.

Jake
  • 600
  • 8
  • 20

2 Answers2

4

If not done yet, install a webserver/servletcontainer like Apache Tomcat.

If you pick Tomcat 6.x, then use Apache Commons FileUpload to get the uploaded file as an InputStream. If you pick Tomcat 7.x (Servlet 3.0), then use HttpServletRequest#getPart() and then Part#getInputStream() to obtain the uploaded file as an InputStream.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2
import org.apache.commons.fileupload.FileItemStream;
 import org.apache.commons.fileupload.FileItemIterator;
 import org.apache.commons.fileupload.servlet.ServletFileUpload;

 import java.io.InputStream;
 import java.io.IOException;
 import java.util.logging.Logger;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 public class FileUpload extends HttpServlet {
   private static final Logger log =
       Logger.getLogger(FileUpload.class.getName());

   public void doPost(HttpServletRequest req, HttpServletResponse res)
       throws ServletException, IOException {
     try {
       ServletFileUpload upload = new ServletFileUpload();
       res.setContentType("text/plain");

       FileItemIterator iterator = upload.getItemIterator(req);
       while (iterator.hasNext()) {
         FileItemStream item = iterator.next();
         InputStream stream = item.openStream();

         if (item.isFormField()) {
           log.warning("Got a form field: " + item.getFieldName());
         } else {
           log.warning("Got an uploaded file: " + item.getFieldName() +
                       ", name = " + item.getName());

           // You now have the filename (item.getName() and the
           // contents (which you can read from stream).  Here we just
           // print them back out to the servlet output stream, but you
           // will probably want to do something more interesting (for
           // example, wrap them in a Blob and commit them to the
           // datastore).
           int len;
           byte[] buffer = new byte[8192];
           while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
             res.getOutputStream().write(buffer, 0, len);
           }
         }
       }
     } catch (Exception ex) {
       throw new ServletException(ex);
     }
   }
 }

The example is extracted from Google App Engine documents since GAE also doesn't allow the application to write files on disk. The original example can be found here

zawhtut
  • 8,335
  • 5
  • 52
  • 76