001package edu.pdx.cs410J.servlets;
002
003import org.apache.commons.fileupload.servlet.ServletFileUpload;
004import org.apache.commons.fileupload.FileItemFactory;
005import org.apache.commons.fileupload.FileUploadException;
006import org.apache.commons.fileupload.FileItem;
007import org.apache.commons.fileupload.disk.DiskFileItemFactory;
008
009import javax.servlet.http.HttpServlet;
010import javax.servlet.http.HttpServletRequest;
011import javax.servlet.http.HttpServletResponse;
012import javax.servlet.ServletException;
013import java.io.IOException;
014import java.io.BufferedReader;
015import java.io.InputStreamReader;
016import java.io.PrintWriter;
017import java.util.List;
018import java.util.Iterator;
019
020/**
021 * A servlet that demonstrates how to upload a file to a web server.  It uses the Apache Commons
022 * <a href="http://commons.apache.org/fileupload">FileUpload</a> library to read the file from the
023 * HTTP request.
024 *
025 * @since Summer 2008
026 */
027public class FileUploadServlet extends HttpServlet {
028
029  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
030    response.setContentType("text/html");
031    PrintWriter pw = response.getWriter();
032    pw.println("<html>");
033    pw.println("<body>");
034
035    if (ServletFileUpload.isMultipartContent(request)) {
036      FileItemFactory factory = new DiskFileItemFactory();
037      ServletFileUpload upload = new ServletFileUpload(factory);
038      List items;
039      try {
040        items = upload.parseRequest(request);
041
042      } catch (FileUploadException ex) {
043        throw new ServletException("Could not upload file", ex);
044      }
045
046      for (Iterator iter = items.iterator(); iter.hasNext(); ) {
047        FileItem item = (FileItem) iter.next();
048        if (item.isFormField()) {
049          // Non-file field in the form
050
051        } else {
052          String fileName = item.getName();
053          String contentType = item.getContentType();
054          pw.println("<h1>You uploaded " + fileName + "</h1>");
055          pw.println("<h2>Content type is " + contentType + "</h2>");
056          
057          if (contentType.equals("text/plain")) {
058            pw.println("<pre>");
059
060            BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream()));
061            while (br.ready()) {
062              pw.println(br.readLine());
063            }
064
065            pw.println("</pre>");
066          }
067        }
068      }
069
070    } else {
071      pw.println("<h1>You did not upload a file?!</h1>");
072    }
073
074    ServletInfoServlet.dump(request, pw);
075
076    pw.println("</body>");
077    pw.println("</html>");
078  }
079}