Commons FileUpload problem

Hello. I want the user to be able to upload a file, and then I want to read the file and do some stuff with it.
I searched around and found out that to do this I needed to use a third party library. I found the Commons FileUpload, but I cant seem to make it work. I tried to use the mailing list, but I have gotten no respons.
In the jsp
***uploadPhoto.jsp ***
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.portlet.*"%>
<%@ page import="org.apache.commons.collections.*"%>
<%@ page import="java.util.*"%>
<%
     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     out.println("" + isMultipart);
//      Parse the request
     FileItemIterator iter = upload.getItemIterator(request);
     while (iter.hasNext()) {
         FileItemStream item = iter.next();
         String name = item.getFieldName();
         InputStream stream = item.openStream();
         if (item.isFormField()) {
             out.println("Form field " + name + " with value "
                 + StreamUtil.asString(stream) + " detected.");
         } else {
             out.println("File field " + name + " with file name "
                 + item.getName() + " detected.");
             // Process the input stream
%>The first line returns true. So I know I have a file. But the next one I get an error saying "Cannot find type FileItemIterator.
I tried to include as much libraries as I thought needed, but still the same error.
I have put the commons fileupload jar in my WEB-INF/lib directory, and also in my application.jar file.
Can someone help me please?
Message was edited by:
asgshe

Yes I found this out right before you posted it.
I think the documentation is very poor. No where did
it say that I needed this. Luckily I read a post here
that someone had suggested this.I have to disagree on that! It is mentioned here: http://jakarta.apache.org/commons/fileupload/using.html and here: http://jakarta.apache.org/commons/fileupload/dependencies.html
Where else should they mention it?

Similar Messages

  • File upload using apache Commons FileUpload problem

    Hi All,
    I have used Commons FileUpload for uploading files from windows to unix machine. I'm able to upload files but I have a problem about the contents of file copied in unix. When i upload files few files containing special characters are not copied correctly in unix instead ascii codes are getting copied/written. Seems to be a problem with character encoding.
    For example symbol "�" is not getting copied correctly in unix. So as new line character to. If anyone has faced such issues kindly provide few pointers on this. Appreciate your guidance.
    Thanks,
    -Aj

    Thanks for the reply.
    I'm using the Commons FileUpload class "FileItem" which holds the filestream data and using function
    code snippet of file upload
    ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
    List fileItemsList = servletFileUpload.parseRequest(request);
    Iterator it = fileItemsList.iterator();
    while (it.hasNext())
         FileItem fileItemTemp = (FileItem)it.next();
         File saveToFile = new File("newFile");
          fileItem.write(saveToFile ); // write fileItem data to saveToFile.
    } FileItem object takes care of writing data to disk.No idea,how it does internally.
    Thanks,
    -Aj.

  • Commons fileupload problem with Jdeveloper

    Hi,
    I tried to use commons fileupload with jdeveloper and I have put those two jar files under web-inf/lib directory. but it did not work. Anyone can help? Thanks in advance. Error code is shown below:
    Error(79,33): illegal start of expressionError: cannot access class org.apache.commons.fileupload.FileItem; file org\apache\commons\fileupload\FileItem.class not found
    Error: cannot access class org.apache.commons.fileupload.FileItemFactory ; file org\apache\commons\fileupload\FileItemFactory.class not found
    Error: cannot access class org.apache.commons.fileupload.FileUpload; file org\apache\commons\fileupload\FileUpload.class not found
    Error: cannot access class org.apache.commons.fileupload.disk.DiskFileItemFactory ; file org\apache\commons\fileupload\disk\DiskFileItemFactory.class not found
    Error: cannot access class org.apache.commons.fileupload.servlet.ServletFileUpload; file org\apache\commons\fileupload\servlet\ServletFileUpload.class not found
    Error: cannot access class org.apache.commons.fileupload.FileUploadBase; file org\apache\commons\fileupload\FileUploadBase.class not found
    Error: cannot access class org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; fileorg\apache\commons\fileupload\FileUploadBase\SizeLimitExceededException.class not found
    Error(25,29): variable ServletFileUpload not found in class _upload
    Error(31,7): class DiskFileItemFactory not found in class _upload
    Error(31,41): class DiskFileItemFactory not found in class _upload
    Error(43,7): class ServletFileUpload not found in class _upload
    Error(43,38): class ServletFileUpload not found in class _upload
    Error(52,15): class SizeLimitExceededException not found in class _upload
    Error(61,7): class FileItem not found in class _upload
    Error(61,24): class FileItem not found in class _upload                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Are you sure you have the full JDK or just JRE?
    Check the size of the jar you downloaded to make sure it downloaded complete.
    Basic install instructions are here:
    http://download.oracle.com/docs/cd/E14571_01/install.1111/e13666/ojdig.htm#BDCJDDFE

  • Jakarta Commons FileUpload ; Internet Explorer Problem

    Hi all,
    Environment:
    Tomcat 5 ;Apache 2; JDK 1.5.0; Jakarta Commons Fileupload 1.0
    OS: Windoze XP
    Previously I've used jakarta commons fileupload package to succussfully to upload a file.
    However, I am trying to check the content type of the file and throw an exception if its not a jpeg file. The following code works great when I use firefox. But it fails when I use Internet Explorer!
    When I supply an existing jpg file on my desktop as the input to the HTML form, the code works fine. However if I enter a non-existing jpg filename, I get a "HTTP 500 Internal Server Error"! I expect to get the "Wrong content type!" message (which my JSP throws as an exception and should be caught by the error page). This problem happens only with Internet Explorer. With firefox, I get the "Wrong Content Type" message as expected.
    What could be the problem? Please advise.
    Thanks
    Joe.
    Code follows......
    /************** file-upload.html *************/
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>File Upload</title>
    <script type="text/javascript" language="JavaScript">
    <!--
    function fileTypeCheck() {
         var fileName = document.uploadForm.pic.value;
         if (fileName == "") {
              alert ("Please select a file to upload!");
              return false;
         var indexOfExt = fileName.lastIndexOf (".");
         if (indexOfExt < 0) {
              alert('You can only upload a .jpg/.jpeg/.gif file!');
              return false;
         var ext = fileName.substring(indexOfExt);
         ext = ext.toLowerCase();
         if (ext != '.jpg' && ext != 'jpeg') {
             alert('You selected a ' + ext + ' file;  Please select a .jpg/.jpeg file instead!');
              return false;
         return true;
    //--></script>
    </head>
    <form action="uploadPhoto.jsp" enctype="multipart/form-data" method="post" name="uploadForm" onSubmit="return fileTypeCheck();">
         <input type="file" accept="image/jpeg,image/gif" name="pic" size="50" />
         <br />
         <input type="submit" value="Send" />
    </form>
    <body>
    </body>
    </html>
    /*************** photoUpload.jsp **************/
    <%@ page language="java" session="false" import="org.apache.commons.fileupload.*, java.util.*" isErrorPage="false" errorPage="uploadPhotoError.jsp" %>
    <%!
    public void processUploadedFile(FileItem item, ServletResponse response) throws Exception {
         try {
              // Process a file upload
                  String contentType = item.getContentType();
              if (! contentType.equals("image/jpeg") && ! contentType.equals("image/pjpeg")) {
                   throw new FileUploadException("Wrong content type!");
         } catch (Exception ex) {
              throw ex;
    %>
    <%
    // Check that we have a file upload requeste
    boolean isMultipart = FileUpload.isMultipartContent(request);
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();
    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);
    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (! item.isFormField()) {
            processUploadedFile(item, response);
    %>
    <html>
    <head>
    </head>
    <body>
    File uploaded succesfully! Thank you!
    </body>
    </html>
    /******** uploadPhotoError.jsp ****/
    <%@ page language="java" session="false" isErrorPage="true" %>
    <html>
    <head>
    </head>
    <body>
    <%
    out.println(exception.getMessage());
    %>
    </body>
    </html>

    I just found out that the problem that I have mentioned in my previous post has nothing to do with Jakarta Commons Fileupload. It happens whenever I try throwing an exception. And it happens only when I use Internet Explorer
    Thanks,
    Joe
    See the code below...
    /**** throw-error.jsp ***/
    <%@ page language="java" session="false" isErrorPage="false" errorPage="catch-error.jsp" %>
    <%
    throw new Exception("Catch this!");
    %>
    /****** catch-error.jsp ****/
    <%@ page language="java" session="false" isErrorPage="true" %>
    <html>
    <head>
    </head>
    <body>
    <%
    out.println(exception.getMessage());
    %>
    </body>

  • Problems with Apache Commons FileUpload

    I'm completely stymied here. I've been trying to get the Apache Commons FileUpload working with a JBoss 4.2 server, and having no luck whatsoever. The servlet is listed out here:
    package com.areteinc.servlets;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;
    public class Filer extends HttpServlet {
         private Logger logger = Logger.getLogger(Filer.class);
         public Filer() {
              logger.setLevel(Level.DEBUG);
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              logger.debug("Serving up a GET page...");
              PrintWriter writer = resp.getWriter();
              StringBuffer response = new StringBuffer();
              response.append("<HTML><HEAD><TITLE>JENA File Uploader</TITLE></HEAD><BODY>");
              response.append("<FORM action=\"Filer\" method=\"POST\" enctype=\"multipart/form-data\">");
              response.append("Upload file: <input type=\"file\" name=\"file1\"/><br>");
              response.append("Upload file: <input type=\"file\" name=\"file2\"/><br>");
              response.append("<input type=submit value=\"Start upload\">");
              response.append("</BODY>");
              writer.println(response);
         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              // First see if someone is uploading more than one file at a time...
              boolean isMultipart = ServletFileUpload.isMultipartContent(req);
              logger.debug("Received a POST request.  Multipart is flagged as " + isMultipart);
              // Create a factory for disk-based file items
              FileItemFactory factory = new DiskFileItemFactory();
              // Create a new file upload handler
              ServletFileUpload upload = new ServletFileUpload(factory);
              // Parse the request
              try {
                   List<FileItem> items = upload.parseRequest(req);
                   Iterator itr = items.iterator();
                   logger.debug("Size of upload is " + items.size() + " items.");
                   while(itr.hasNext()) {
                        FileItem item = (FileItem) itr.next();
                        logger.debug("Filename is " + item.getName());
              } catch (FileUploadException e) {
                   e.printStackTrace();
    }When run, I hit it with a get operation, and get the form. When I put in 2 forms (in reality, all i want to do is use one, but I'm tinkering), I see nothing in items list...
    Run, with 2 files selected to upload:
    13:50:15,421 DEBUG [Filer] Received a POST request. Multipart is flagged as true
    13:50:15,421 DEBUG [Filer] Size of upload is 0 items.
    I've tried variation after variation after variation, and it jst doesn't work. I'm using commons-fileupload-1.2.1.
    Help! :)

    On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For your case,
    The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.
    When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.
    Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.
    Jason Hunter's MultipartRequest (available from [http://www.servlets.com/])
    Apache Jakarta Commons Upload (package org.apache.commons.upload) "makes it easy to add robust, high-performance, file upload capability to your servlets and web applications"
    *CParseRFC1867 (available from [http://www.servletcentral.com/]).
    *HttpMultiPartParser by Anil Hemrajani, at the isavvix Code Exchange
    *There is a multipart/form parser availailable from Anders Kristensen ([http://www-uk.hpl.hp.com/people/ak/java/] at [http://www-uk.hpl.hp.com/people/ak/java/#utils].
    *JavaMail also has MIME-parsing routines (see the Purple Servlet References).
    *Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the Tomcat CVS tree.
    *JSPSmart has a free set of JSP for doing file upload and download.
    *UploadBean by JavaZoom claims to handle most of the hassle of uploading for you, including writing to disk or memory.
    There's an Upload Tag in dotJ
    Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.
    Please note: that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.
    I still have doubt if all the moentioned resources are alive or not

  • Problem with commons.fileupload

    I'm using Tomcat 4.1 and before I couldn't get the compiler to find the package until I put it in my %JAVA-HOME%\jre\lib\ext folder. After I did that I could compile just fine. Now when I try uploading a file I get 'NoClassDefFoundError'. I read that this is because I have the jar file in both the %JAVA-HOME% and WEB-INF\lib . I tried running it without having it in %JAVA-HOME% and it made no difference. If anyone can help I would really appreciate it. Thanks.

    I suggest taking a look at the user guide, they do some things differently than you do:
    http://jakarta.apache.org/commons/fileupload/using.html

  • Problem with Commons FileUpload and ssl

    Hi,
    i want to send to servlet mulipart form data using ssl:
    this is my html page:
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>simple form page</title>
        </head>
        <body>
            <form method="POST" enctype="multipart/form-data" action="SimpleResponseServlet">
                <br><input type=file name=upfile></input></br>
                <br><input type=text name=note></input></br>
                <br><input type=submit value=Press></input></br>
             </form>
         </body>
    </html>This is code from SimpleResponseServlet:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
       response.setContentType("text/plain;");
       PrintWriter out = response.getWriter();
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       System.err.println(isMultipart);
       try{
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = upload.parseRequest(request);
             Iterator iter = items.iterator();
                while(iter.hasNext())
                     FileItem item = (FileItem) iter.next();
                     System.out.println(item.getContentType());
                     System.out.println(item.getFieldName());
                     System.out.println(item.getName());
                     System.out.println(item.isFormField());
           out.println("ok");
      catch(Exception ex){
       System.out.println(ex.toString());
      finally{ 
        out.close();
            this is what Tomcat 6.0 console show using https to call servlet:
    false
    org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException:the request doesn't contain a multipart/form-data or multipart/mixed-stream, content type header is null.if i use normal http servlet works fine.
    Help me, please.
    Thank you,
    David.

    I have replaced in html page this attribute:
    action="SimpleResponseServlet"with this:
    action="https://localhost:8443/ProvaImageReaderServlet/SimpleResponseServlet"and servlet can read items because there's not redirecting.
    But is it a clear way call directly servlet with https???
    Thank you....

  • Attachements with apache commons fileupload

    I'm using:
    http://commons.apache.org/fileupload/
    to write file on server side (Tomcat running on Windows with XP or 2003).
    I'm sending data to servlet with doPost() as follows:
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(4096);
                factory.setRepository(new File("test"));
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(1000000);
                List fileItems = upload.parseRequest(request);
                Iterator i = fileItems.iterator();
                String comment = ((FileItem) i.next()).getString();
                FileItem fi = (FileItem) i.next();
                String fileName = fi.getName();
                // db
                fi.write(new File("C:/", fileName));
            } catch (Exception ex) {
                out.print(ex.getMessage());
            out.close();
        }but it's response is:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: Servlet execution threw an exception
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
    root cause
    java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
         org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
         org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
         Upload.doPost(Upload.java:69)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
    root cause
    java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
         java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
         org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
         org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
         org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
         Upload.doPost(Upload.java:69)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.
    Apache Tomcat/6.0.16don't know why.. any ideas?

    java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStreamThe mentioned class is missing in the runtime classpath.
    Add it (in this specific case, the JAR file with the mentioned class) to the classpath and the problem will disappear.
    This class is part of Commons IO. Read the dependencies page at FileUpload user guide which JAR's you all need.

  • Apache commons fileUpload parseRequest finds no form fields-portalComponent

    Hello All,
    What am I trying?
    Developing a portal component (no JSP, no HTMLB).
    Have used Apache commons fileUpload libraries.
    What is the problem?
    parseRequest method works fine when I right click and preview from PCD.
    parseRequest method returns 0 html form elements when the portal component is tested under the TLN (via role -> workset -> iview)
    What else did I try?
    1.
    I looked in to Apache documentation - there are two different APIs for two different scenarios, Servlets and Portlets.
    My understanding is that I can not use portlets scenario in SAP Portal.
    Servlets scenario was what worked while doing a preview from PCD.
    2. I have looked into other solutions like using web dynpro and HTMLB to do file upload - not really a fan of either for various reasons.
    Can any one help?
    I am trying to understand why the HTTPServletRequest when parsed returns 0 form elements in the SAP Portal scenario.
    Thanks!

    Hello Ankur,
    You said:
    The reason for this is, unlike the request parameters, the multipart formdata is 'read-once-only' (because once
    the data is read off the ServletInputStream, it is gone! It cannot be read again). When you call a full portal request it goes through lot of gets before reaching your component.
    The above concept is not fully clear to me. I got a hint to something like this happening from this link that explains the need for portlets API scenario compared to a servlets scenario - Link: http://commons.apache.org/fileupload/using.html
    (Search for Servlets and Portlets within that link)
    I initially thought something like what you had replied would have happened. However, when I do a getContentLength on HTTPServletRequest in the SAP Portal mode (role -> workset -> iview), the size still includes that of the uploaded document. So like you said "it is gone! It cannot be read again" may not be accurate.
    My question still remains open.
    Edited by: Mohammed on Aug 24, 2009 6:29 PM

  • Apache commons FileUpload: Pass stream as attribute

    I'm trying to implement a Filter that will change all the HTTP parameters to attributs, so that I can handle them in a consistent way throughout my servlets. The apache commons fileupload part is giving me problems. I'm changing the parameters to attributes like this
    if(URLENCODED.equalsIgnoreCase(contentType) || contentType == null) // Used with normal form data
      Enumeration<String> params = request.getParameterNames();
      while(params.hasMoreElements())
        String name = params.nextElement();
        String value = request.getParameter(name);
        request.setAttribute(name, value);
    else if(contentType.toLowerCase().startsWith(MULTIPART))     // Used when file is uploaded with POST               
      // Create file upload handler
      ServletFileUpload upload = new ServletFileUpload();
      FileItemIterator iter;
      iter = upload.getItemIterator((HttpServletRequest) request);
      while(iter.hasNext())
        FileItemStream item = (FileItemStream)iter.next();
        InputStream itemStream = item.openStream();
        if(item.isFormField())          // form item
          BufferedReader rd = new BufferedReader(new InputStreamReader(itemStream));
          String line;
          while((line = rd.readLine()) != null)
            streamParamsToAttributes(line)
      else          // file
        request.setAttribute("filestream", itemStream);
    }In my servlet I use the file stream with following code
    InputStream itemStream = (InputStream)(request.getAttribute("filestream"));
    useStream(itemStream)Here the useStream() method will throw a FileItemStream.ItemSkippedException since I'm trying to read data from the stream after the iter.next() was called.
    So my question is, how to handle this kind of situation? The file can be quite big, so reading it to memory is not wise. And as I read, copying the stream is not a straight-forward task.
    I noticed that O'Reilly has also a library for handling file uploads, is it any better in this case?
    Thanks.

    I looked at the O'Reilly lib and it seems to always save the file to disk. So no streaming possibility.
    One solution I can think of would be to 'manually' read the data from the request. I can get the data with request.getReader() call. The file data can be found by the boundary. Now I'm wondering whether this will solve anything. Can anyone see some caveats in this approach?

  • Commons fileupload exception

    when i use commons fileupload to do file uploading, i got an exception
    "javax.servlet.ServletException: Servlet execution threw an exception
    fileters.ExampleFilter.doFilter(ExampleFilter.java:101)"
    root cause:
    "java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
    anyone can tell me:
    What does it mean and how can i solve this problem?
    Shall I import commons io jar to implement file uploading?
    Thanks

    I am having the this exception though I have placed both the jars in web-Inf/lib(commons-io-1.1.jar AND commons-fileupload-1.1.jar
    any thoughts where it mightbe going wrong.
    Do I need to update any other jar files as well.

  • Commons fileupload suddenly very slow

    I've been using the commons fileupload for a couple of years with no problem. Suddenly though it's started to work impossibly slowly. I updated to the most recent version, but still no luck.
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    java.util.List items = upload.parseRequest(request);The third line of this code is taking about 30 seconds to run - even with only one image. Previously it was handling multiple images faultlessly.
    Does anyone have any ideas?
    Cheers
    D

    Hello,
    Check to see how much free disk space there is. Right or control click the MacintoshHD icon on your Desktop, then click: Get Info. In the Get Info window, click the discovery triangle so it's facing down. You will see; Capacity and Available Make sure you have 10% available disk space, 15% is better. Insufficient available space, can cause performance issues, system corruption, and possible loss of data.
    Check the hard disk for errors.
    Insert Installer disk and Restart, holding down the "C" key until grey Apple appears.
    Go to Installer menu (Panther and earlier) or Utilities menu (Tiger and later) and launch Disk Utility.
    Select your HDD (manufacturer ID) in the left panel.
    Select First Aid in the Main panel.
    (Check S.M.A.R.T Status of HDD at the bottom of right panel. It should say: Verified)
    Click Repair Disk on the bottom right.
    If DU reports disk does not need repairs quit DU and restart.
    If DU reports errors Repair again and again until DU reports disk is repaired.
    Read the post by "Klaus1" here. http://discussions.apple.com/thread.jspa?messageID=7668937#7668937
    52 Ways to speed up Mac OS X
    Carolyn

  • Commons-Fileupload question

    Hi,
    I'm trying to use the commons-fileupload-1.1.jar file and I've placed it in my WEB-INF/lib folder. When I try to compile my java though, I get an error that reads: package org.apache.commons.fileupload does not exist. I'm importing like this:
    import org.apache.commons.fileupload.DiskFileUpload;
    I've searched for answers on this already but can't find anything. I don't know if I'm placing it in the wrong folder or what. I'm using Tomcat so I also tried placing the jar file in the common/lib and server/lib folders but neither solved the problem. I've read that I may need to set in my classpath, but I don't know how to do this. Any help is appreciated. Thanks

    I'm trying to use the commons-fileupload-1.1.jar
    ar file and I've placed it in my WEB-INF/lib folder.
    When I try to compile my java though, I get an error
    r that reads: package
    org.apache.commons.fileupload does not exist.
    I'm importing like this:
    import org.apache.commons.fileupload.DiskFileUpload;Placing the jar in the WEB-INF/lib is the correct thing to do. But this would take care of the runtime. For compilation, you HAVE to set the jar to the classpath.
    javac -classpath "%CLASSPATH%;c:\Tomcat\MyApp\WEB-INF\lib\commons-fileupload-1.1.jar" MyClass.javaThis is how your command should look.
    I would rather suggest you to use Ant and create a simple build script to take care of all the compilation and classpath part.

  • Commons-fileupload-1.2.1. 4 kB limit

    Hi everybody.
    I am using apache commons-fileupload-1.2.1.jar to upload files (multipart data). I have copy/pasted the code from their example page:
    [http://commons.apache.org/fileupload/streaming.html]
    However, I have problems. When I open the inputStream to a file, and check for stream.available(), it always returns 3904 - 3916. And then I write that data down to a blob and from there save it to a file and the file is always 4 kB long.
    I have checked the limits of my Apache Tomcat. It allows files up to 20 MB.
    I have used this code to get the data:
                File tem = new File("/");
                FileItemFactory factory = new DiskFileItemFactory(10000000,tem);
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload();
                // Parse the request
                // maximum size before a FileUploadException will be thrown
                upload.setSizeMax(10000000);
                upload.setFileSizeMax(10000000);
                upload = new ServletFileUpload(factory);
                // Parse the request
                FileItemIterator iter = upload.getItemIterator(request);
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    String name = item.getFieldName();
                    InputStream stream = item.openStream();
                    if (item.isFormField()) {
                         // source to do with form fields   
                    } else {
                        BufferedInputStream bis = new BufferedInputStream(stream, 1000000);
                        out.println("Stream has: " + stream.available());
                        // prints out 3904 - 3916, depends on the file
                        byte[] temp = new byte[stream.available()];
                        int bytesRead = stream.read(temp );
                        out.print("Number of bytes read: " +bytesRead + "<br>");
                        // prints out 3904 - 3916, depends on the file
                Any ideas what to add or where the 4 kB limit is?

    It's indeed a blocking/buffered stream. Commons FileUpload comes along with excellent documentation and examples of how to use it. Go read them. Especially the 'User Guide' and 'Frequently Asked Questions' sections at their homepage.
    If you really want to know the content length beforehand, you need HttpServletRequest#getContentLength(). Only keep in mind that the client has full control over the request header values, so your code shouldn't rely that much on this.
    That said, in the future you should be posting Servlet related questions at the Servlet forum.

  • Apache Jakarta Commons FileUpload misleading message

    I have a JSP page doing file upload using commons FileUpload package. The code looks like this:
    <%
    DiskFileUpload upload = new DiskFileUpload();
    List items = upload.parseRequest(request);
    Iterator itr = items.iterator();
    while(itr.hasNext()) {
         FileItem item = (FileItem) itr.next();
         // check if the current item is a form field or an uploaded file
         if(item.isFormField()) {
              String fieldName = item.getFieldName();
              if(fieldName.equals("name"))
                   request.setAttribute("msg", "Thank You: " + item.getString());
         } else {
              File fullFile = new File(item.getName());
              File savedFile = new File("c:\\tmp\\",     fullFile.getName());
              item.write(savedFile);
    %>
    The JSP successfully uploaded the files but it still show me HTTP Status 404 - c:\tmp (Access is denied).
    What's wrong with my code? Thank you.

    I just found out that the problem that I have mentioned in my previous post has nothing to do with Jakarta Commons Fileupload. It happens whenever I try throwing an exception. And it happens only when I use Internet Explorer
    Thanks,
    Joe
    See the code below...
    /**** throw-error.jsp ***/
    <%@ page language="java" session="false" isErrorPage="false" errorPage="catch-error.jsp" %>
    <%
    throw new Exception("Catch this!");
    %>
    /****** catch-error.jsp ****/
    <%@ page language="java" session="false" isErrorPage="true" %>
    <html>
    <head>
    </head>
    <body>
    <%
    out.println(exception.getMessage());
    %>
    </body>
    </html>

Maybe you are looking for

  • Display Images from  HTMLDB_APPLICATION_FILES Table?

    How do I display images from the HTMLDB_APPLICATION_FILES Table? Are the contents full available potentially for display? Or only after I have written them to another display? Please advise what I need to do or what corrections below is required: The

  • Where can I find my mountain lion installer included with 2012 mac mini

    I just bought a 2012 mac mini and I want to install mountain lion on an SSD that I bought separately.  Where can I find the mountain lion installer file to create a bootable USB install drive?  When I go to the mac app store, mountain lion is not lis

  • Mutilple contacts

    Multiple contacts. My contact list is littered with contact info 10X over. Each person has sometimes over  6 profiles in my contacts list. How do I manage all of this? And by manage I mean delete them forever?

  • No movies

    my atv does not load the library of movies. sending in play from itunes on mac pro the movie starts. Returning to the library on apple tv in the list only appears the film sent from mac. 1 uprgrade pending... mmm i try it

  • Thermalright IFX-14: How to make it worth the money

    Right, I spent 2 days pondering on how to get this going like it should. Thermalright's IFX-14 is certainly a mixed bag. It's the best air cooling you can most likely buy, but getting it to work is the hardest part of it. My story: Day 1: It arrives,