Java.io.File vs. Jakarta Commons Upload

Does anyone know what the difference is between using Jakarta Commons Upload functionality vs. using Java's File API? It seems I could simply use Java's API with the same results. Is there some major difference between the two that I'm missing?

Does anyone know what the difference is between using
Jakarta Commons Upload functionality vs. using Java's
File API? It seems I could simply use Java's API
with the same results. Is there some major
difference between the two that I'm missing?I guess one's to upload files using a servlet while the other one's for modelling a path in the local file system...
About the difference between a parking lot and the car in your driveway.

Similar Messages

  • File upload with jakarta common upload package

    i got the code f file upload from the forum but it is not working and giving some errors . I am attaching the code iam using and the stack trace of the errors i am getting . Please if somebody can help me ............
    <html>
    <form method="post" action="/servlet/UploadFile" enctype="multipart/form-data">
    Name
    <input type="text" name="uname"/>
    File
    <input type="file" name="upfile"/>
    <input type="submit"/>
    </form>
    </html>
    and the servlet handling the request is as import java.io.File;
    import java.io.IOException;
    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.DiskFileUpload;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUpload;
    import org.apache.commons.fileupload.FileUploadException;
    * @author sm23772
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class UploadFile extends HttpServlet {
    public void doPost(HttpServletRequest req,HttpServletResponse res)
    public class UploadFile extends HttpServlet {
    public void doPost(HttpServletRequest req,HttpServletResponse res)
    try{
    FileUpload fup=new FileUpload();
    boolean isMultipart = FileUpload.isMultipartContent(req);
    // Create a new file upload handler
    System.out.println(isMultipart);
    DiskFileUpload upload = new DiskFileUpload();
    // Parse the request
    List /* FileItem */ items = upload.parseRequest(req);
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField()) {
    System.out.println("its a field");
    } else {
    System.out.println("its a file");
    System.out.println(item.getName());
    File cfile=new File(item.getName());
    File tosave=new File(getServletContext().getRealPath("/"),cfile.getName());
    }catch(Exception e){System.out.println(e);}
    the exception arising are
    as ..........
    exception
    javax.servlet.ServletException: Cannot allocate servlet instance for path /servlet/UploadFile
         org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:389)
         org.apache.catalina.servlets.InvokerServlet.doPost(InvokerServlet.java:170)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    root cause
    java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileUpload
         java.lang.Class.getDeclaredConstructors0(Native Method)
         java.lang.Class.privateGetDeclaredConstructors(Class.java:2328)
         java.lang.Class.getConstructor0(Class.java:2640)
         java.lang.Class.newInstance0(Class.java:321)
         java.lang.Class.newInstance(Class.java:303)
         org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:370)
         org.apache.catalina.servlets.InvokerServlet.doPost(InvokerServlet.java:170)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileUpload
    this is your error
    you need to have commons-fileupload-1.2.jar in your classpath
    you can download it from http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi

  • Uploading a file to server using servlet (Without using Jakarta Commons)

    Hi,
    I was trying to upload a file to server using servlet, but i need to do that without the help of anyother API packages like Jakarta Commons Upload. If any class for retrieval is necessary, how can i write my own code to upload from client machine?.
    From
    Velu

    <p>Why put such a restriction on the solution? Whats wrong about using that library?
    The uploading bit is easy - you put a <input type="file"> component on the form, and set it to be method="post" and enctype="multipart/form-data"
    Reading the input stream at the other end - thats harder - which is why they wrote a library for it. </p>
    why i gave the restriction is that, i have a question that <code>'can't we implement the same upload'</code>
    I was with the view that the same can be implemented by our own code right?

  • J2EE BluePrints: correct location for common Java source files

    I have a set of Java source files that are common between multiple J2EE applications.
    Within the J2EE package hierarchy, what is the correct location for these files?
    Also, is there a typical package name that common Java source files are grouped under?

    HI,
    There is no standard place. In the blueprints project conventons
    http://java.sun.com/blueprints/code/projectconventions.html it has a place called components/ which would contain shared components like EJBs and other components that could be shared across applications. the package naming would be reflected in that, like com.sun.blueprints.application1. and com.sun.blueprints.application2. and com.sun.blueprints.common.*
    Generally you could put a directory at the same level as the apps (not inside an app's directory structure) and maybe called common/ or shared/ . This common code could be built separtely and into a binary library or jar that you just include in the other applicatons, in the same way you would include some external library jar that you got somewhere and keep in your workspace and your apps use. The packaging of common code is similiar to the packaging of different applications and shared components.
    hth,
    Sean

  • Jakarta Commons -- File Upload does not work with Application Server

    Hi ALl,
    I tried Jakarta Commons file upload. In the netbeans, I copied the common jar files "commons-io-1.2.jar" and "commons-fileupload-1.1.1.jar" in the
    netbeans-5.5\enterprise3\apache-tomcat-5.5.17\common\lib and set the class paths. It is working correctly when I compile and run from the netbeans. However, when I deployed in Sun Application Server PE 9.0, I am receiving the following errors. In Sun application I copied the above jars files to "C:\Sun\AppServer\jdk\jre\lib\ext"..
    I have read in several postings that it does not work this way but could find any solution. Any idea will be greatly appreciated.
    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: java.lang.NoClassDefFoundError: javax/servlet/ServletInputStream
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:930)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:863)
         org.apache.jsp.fileUpload_jsp._jspService(fileUpload_jsp.java:109)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:353)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:409)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:317)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:73)
         com.sun.enterprise.web.VirtualServerPipeline.invoke(VirtualServerPipeline.java:120)
         org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:231)
         com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter(ProcessorTask.java:667)
         com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked(ProcessorTask.java:574)
         com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:844)
         com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:287)
         com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:212)
         com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:252)
         com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:75)
    root cause
    java.lang.NoClassDefFoundError: javax/servlet/ServletInputStream
         org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:116)
         org.apache.jsp.fileUpload_jsp._jspService(fileUpload_jsp.java:76)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:353)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:409)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:317)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:73)
         com.sun.enterprise.web.VirtualServerPipeline.invoke(VirtualServerPipeline.java:120)
         org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:231)
         com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter(ProcessorTask.java:667)
         com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked(ProcessorTask.java:574)
         com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:844)
         com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:287)
         com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:212)
         com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:252)
         com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:75)
    note The full stack trace of the root cause is available in the Sun Java System Application Server Platform Edition 9.0 logs.
    Sun Java System Application Server Platform Edition 9.0
    Thank you,
    --Sam                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi All,
    I solved this few minutes after I posted this question. Thought I should share with everybody, just in case some one else need it.
    I copied these three files in the folder C:\Sun\AppServer\jdk\jre\lib\ext
    1. servelet-api.jar
    2. commons-io-1.2.jar
    3. commons-fileupload-1.1.1.jar
    No need to set any class path.
    Thanks

  • JSP error java.lang.NoClassDefFoundError: org/apache/commons/fileupload/Fil

    I'm rather new to jsp. I'm using myeclipse and I'm deploying my site on tomcat. I've been slowly working away on the errors in my log files. Most of the problems that I've run into have been missing jar files. The log error that I'm stuck on follows:
    10:14:40,359 ERROR [Faces Servlet]:253 - Servlet.service() for servlet Faces Servlet threw exception
    java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileUpload
         at org.apache.myfaces.component.html.util.ExtensionsFilter.doFilter(ExtensionsFilter.java:115)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at com.wolverinecrane.view.util.SecurityFilter.doFilter(SecurityFilter.java:77)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    In my buildpath I have commons-fileupload-1.0.jar which includes org.apache.commons.fileupload which has the class FileUpload.class in it.
    Any help on what may be going wrong here would be appreciated.
    Dan

    Solved:
    http://javalive.com/modules/newbb/viewtopic.php?topic_id=355&post_id=1013&order=0&viewmode=flat&pid=0&forum=4#forumpost1013

  • Java bean File Upload - Error-105101

    We were having earlier the same problem of 105100 error. As the solution, suggested earlier in the thread posted by Teguh Santoso, the classpath settings that was mentioned ealier was done, the certificate was imported in the client machine.
    At the web-browser-client machine, the "Select" button in the "fileupload" demo form is opening the FileDialog(that cleared the earlier problem). But on selecting a file in it, the error ORA-105101 is occuring for the WHEN-CUSTOM-ITEM-EVENT..... But both the progress bars, the one that is there for encoding of the seleced file, and the one that is there for the uploading gets displayed. On searching the "c:\temp" folder(folder where the file is intended to be uploaded to) of the application server, we see that the particular file has not been uploaded.
    The same thing is working alright when we do it in the 9iAS machine, when using the "Run on Web" option in the 6i-FormBuilder.
    What additional settings are to be done for using the file-upload utility through web-forms? Please help..
    Thank you
    Regards
    Ranjith.

    If you press KEY-LISTVAL in the Upload demo form it will message out the current classpath for you. If that fails as well it's because the basic Java Runtime classes cannot be found.
    The general things to have to watch in the setup (on the Application server) are:
    1) A Java 1.2.2+ runtime environment is available
    2) The /jre/bin/classic directory is in the O/S PATH for Windows, or the LD_LIBRARY_PATH for SOLARIS or the SHLIB_PATH for HP. This is so that Forms can locate the JVM.DLL (Windows) or libjvm.sl/so (UNIX)
    3) The CLASSPATH needs to contain the 1.2.2+ Java runtime jar file rt.jar. This is in the /jre/lib directory.
    4) The CLASSPATH should of course also contain the UploadServer.jar

  • File upload using commons-upload-file and tomcat 5.5

    Hi,
    This is my first post and I hope that I post it at the right place.
    I'm trying to upload a file using commons-upload-file and tomcat 5.5.
    Is there a way to prevent submitting a big file, If I detect that the file being uploaded exceed a limit that I have fixed ?
    i.e. I check the request length, if it's bigger than 1meg I cancel the whole thing and the big file is not transferred.
    The problem that I get at the moment is that it seems that the file is transferred even if I close request inputstream or response outputstream. Any help would be appreciated !
    Thank you
    Redgy

    Well here is a snippet of my code:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            long maxSize = 50000;
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if(isMultipart){
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload();
                upload.setSizeMax(maxSize);
                try {
                    upload.parseRequest(request);
                } catch (FileUploadException ex) {
                    ex.printStackTrace();
                    request.getInputStream().close();
                    response.getWriter().print("blah");
                    response.sendError(response.SC_INTERNAL_SERVER_ERROR);
                    response.getOutputStream().close();
        }If the file is bigger than 50kb, it Throws the FileUploadException.
    But whatever I do, It seems that there is still a connection between my browser and tomcat.. any clue ?
    thanks
    Edited by: redgyx on Jan 31, 2008 6:17 AM

  • 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>

  • Java.io.File - pathnames on tomcat

    Hi,
    I am trying to implement a file upload feature on my website using Flash 8 and jakarta commons FileUpload.
    I'm running into problems with the java.io.File class. I want to save uploaded files in a folder not relative to the calling page's context.
    When I use the following three lines, the files get saved correctly (in an "/uploads" folder in the current context):
    File fullFile = new File(item.getName());
    File savedFile = new File(getServletContext().getRealPath("/uploads"), fullFile.getName());
    item.write(savedFile);
    However, when I use the following instead of the second line, I get an http 500 error:
    File savedFile = new File("/absolute/path/to/another/context/uploads", fullFile.getName());
    What's strange is when I put in a println, I see that
    getServletContext().getRealPath("/uploads") = /usr/local/tomcat/webapps/mywebapp/uploads
    However, when I substitute the string in the new File(String parent, String child) method, I also get a http 500 error:
    File savedFile = new File("/usr/local/tomcat/webapps/mywebapp/uploads", fullFile.getName());
    This is the stack trace:
    2006-02-03 12:12:05 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp
    threw exception
    org.apache.jasper.JasperException: /upload.jsp(11,2) Unterminated <% tag
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorH
    andler.java:39)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.j
    ava:409)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.j
    ava:134)
    at org.apache.jasper.compiler.Parser.parseScriptlet(Parser.java:796)
    Am I understanding the methods incorrectly?
    Any help would be greatly appreciated! I am completely stuck
    Thank you.

    Thanks. I must have deleted the "%>" by accident while I was fiddling with the code (this is what happens when you look at the same code for too long!!). That explains why File savedFile = new File("/usr/local/tomcat/webapps/mywebapp/uploads", fullFile.getName()); didn't work earlier. Now it does.
    However, the following still does not work:
    ile savedFile = new File("/absolute/path/to/another/context/uploads", fullFile.getName());
    This is the stack trace:
    Generated servlet error:
    /usr/local/jakarta-tomcat-5.0.28/work/Catalina/www.jupiterhotelvideo.com/_/org/a
    pache/jsp/upload_jsp.java:39: 'try' without 'catch' or 'finally'
    try {
    ^
    Generated servlet error:
    /usr/local/jakarta-tomcat-5.0.28/work/Catalina/www.jupiterhotelvideo.com/_/org/a
    pache/jsp/upload_jsp.java:109: '}' expected
    ^
    3 errors
    at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErro
    rHandler.java:84)
    at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher
    .java:332)
    at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:412)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:472)
    Do you know what the problem could be?
    I will try sroot's suggestions to reference another servletcontext...though the place where I'd like to put the "/uploads" folder isn't a web application, but just a directory on my server....
    Thanks for your help; online forums are a life-saver!!!
    That means your JSP
    doesn't compile because of a syntax error. Most
    likely you are missing one of the two " characters
    that delimit a string, so your %> closing tag looks
    like part of the string.

  • Java.io.File constructor - pathnames on tomcat

    Hi,
    I am trying to implement a file upload feature on my website using Flash 8 and jakarta commons FileUpload.
    I'm running into problems with the java.io.File class. I want to save uploaded files in a folder not relative to the calling page's context.
    When I use the following three lines, the files get saved correctly (in an "/uploads" folder in the current context):
    File fullFile = new File(item.getName());
    File savedFile = new File(getServletContext().getRealPath("/uploads"), fullFile.getName());
    item.write(savedFile);
    However, when I use the following instead of the second line, I get an http 500 error:
    File savedFile = new File("/absolute/path/to/another/context/uploads", fullFile.getName());
    What's strange is when I put in a println, I see that
    getServletContext().getRealPath("/uploads") = /usr/local/tomcat/webapps/mywebapp/uploads
    However, when I substitute the string in the new File(String parent, String child) method, I also get a http 500 error:
    File savedFile = new File("/usr/local/tomcat/webapps/mywebapp/uploads", fullFile.getName());
    This is the stack trace:
    2006-02-03 12:12:05 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp
    threw exception
    org.apache.jasper.JasperException: /upload.jsp(11,2) Unterminated <% tag
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorH
    andler.java:39)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.j
    ava:409)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.j
    ava:134)
    at org.apache.jasper.compiler.Parser.parseScriptlet(Parser.java:796)
    Am I understanding the methods incorrectly?
    Any help would be greatly appreciated! I am completely stuck
    Thank you.

    May be the security manager is not allowing to save files in the folders outside your context.
    Put your code within a try catch block and see it there is any exception and if yes print the stack trace and look whats in it

  • 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>

  • Trying a comprehensive jakarta-commons PKGBUILD....

    Hey there!
    I would like to build a PKGBUILD for a nice java banking program. On the way to a Arch-conform PKGBUILD I stumbled over the Java Package Guidelines and investigated the libs which are shipped with the program a bit further.
    There I found that some jars from the jakarta commons package were used but not yet packaged in AUR or the official repos. So first I wanted to build them separately, but then I found that it would make more sense to have one comprehensive package of (currently) 30MB instead of 33 single packages.
    What do you think about the idea? I am willing to support this meta package as well as the single ones if I just knew how the implementation would be more sensible.
    Since it would be a huge amount of work to pack every packag on its own, I wrote a PKGBUILD for all packages that are in Jakarta Commons.
    I hope, if it is generally desired to have any package in a single file, that I at least learnt a bit from writing this PKGBUILD
    # Contributor: jakob
    pkgname=jakarta-commons-all
    pkgver=1.0
    pkgrel=1
    pkgdesc="This packag includes all Jakarta Commons Proper packages."
    url="http://jakarta.apache.org/commons/"
    license="APACHE"
    depends=()
    makedepends=()
    conflicts=()
    source=(http://www.apache.org/dist/jakarta/commons/attributes/binaries/commons-attributes-2.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/beanutils/binaries/commons-beanutils-1.7.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/betwixt/binaries/commons-betwixt-0.7.tar.gz
    http://www.apache.org/dist/jakarta/commons/chain/binaries/commons-chain-1.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/cli/binaries/cli-1.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/codec/binaries/commons-codec-1.3.tar.gz
    http://www.apache.org/dist/jakarta/commons/collections/binaries/commons-collections-3.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/configuration/binaries/commons-configuration-1.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/daemon/binaries/commons-daemon-1.0.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/dbcp/binaries/commons-dbcp-1.2.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/dbutils/binaries/commons-dbutils-1.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/digester/binaries/commons-digester-1.7.tar.gz
    http://www.apache.org/dist/jakarta/commons/discovery/binaries/commons-discovery-0.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/el/binaries/commons-el-1.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/email/binaries/commons-email-1.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/fileupload/binaries/commons-fileupload-1.1.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/httpclient/binary/commons-httpclient-3.0.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/io/binaries/commons-io-1.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/jelly/binaries/commons-jelly-1.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/jexl/binaries/commons-jexl-1.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/jxpath/binaries/commons-jxpath-1.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/lang/binaries/commons-lang-2.2.tar.gz
    http://www.apache.org/dist/jakarta/commons/latka/binaries/latka-1.0-alpha1.zip
    http://www.apache.org/dist/jakarta/commons/launcher/binaries/commons-launcher-1.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/logging/binaries/commons-logging-1.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/math/binaries/commons-math-1.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/modeler/binaries/commons-modeler-2.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/net/binaries/commons-net-1.4.1.tar.gz
    http://www.apache.org/dist/jakarta/commons/pool/binaries/commons-pool-1.3.tar.gz
    http://www.apache.org/dist/jakarta/commons/primitives/binaries/commons-primitives-1.0.tar.gz
    http://www.apache.org/dist/jakarta/commons/scxml/binaries/commons-scxml-0.5.tar.gz
    http://www.apache.org/dist/jakarta/commons/transaction/binaries/commons-transaction-1.1.tgz
    http://www.apache.org/dist/jakarta/commons/validator/binaries/commons-validator-1.3.0.tar.gz)
    md5sums=('47d037449aa38b6c8e181abcfaf36b2b' 'd1571ce9d6ec3d1795364cc44f3d116e'
    '707af78be5ed2518dd2eada9afefb238' 'e688f648a5fd324f591669ca70ebe96d'
    '6c28bdee998fe4d9e76c7cf40e7f4691' 'aad3948be13476d9599cadaf146bc92a'
    '030a1c1d08f47a6c9be000fc611714b4' '6c8bc440de20b7c9b5b3b5315d50316b'
    '591fceeb4feab1094a78c9c5decd8cca' 'd333fc11abb532be2487338cb452b583'
    'b437ea809d320378fc05af9f29e2636f' '717239578dfcd05bde0dfd1d3e8f319f'
    '2273f5f83a477f4f18fccf3a00e2b48c' 'fb856b9689bdc4c52f8ae999057f89fc'
    '4fb252cd4bcee57b573937e3c88974cc' '3b851898d3347cd4d6890b79c9a8a0f0'
    '58167f247e8f8ad8fb1def97c1de8f07' '52b42b61593def482dc968ffdd27f113'
    'e9e3ba84a214d2bcf96aa31b24f3bb5f' '9bdf02d9b659a70b7f327c923c1f4d80'
    '1730dae5f0ef0594a47ead5d1a4ac41b' '4f683f7b6970babb8c9f09bb12b7c1a6'
    'fbf479099aa252989fe4c81511abf4bf' '7ed65e08e8c952c4d9f6db0d73ef5426'
    'c2bd7cc1fa08d78ec5aa80632c21152b' '37c43d1d0c08c1b753a7bf952c763eb3'
    'ba74fdf4aca98f01579eca11acc6d882' '577e90cc40328c287acc921dae344c12'
    '1bdae6c015689349b704daebda924a5b' '2ce92656204f2fa63dad6dfa88e1458b'
    '091e2dc0efcb9155c2b4a05792d49a77' 'fe946d1775d58ded6050dec6af648f38'
    '221d924fb85f3597d8be0708d45f0f5a')
    build() {
    mkdir -p $startdir/pkg/usr/share/java/jakarta-commons
    cd $startdir/src/
    rm -rf *gz docs LICENSE*
    mv *.txt doc
    mv * $startdir/pkg/usr/share/java/jakarta-commons
    Since there are sometimes when copy&pasting PKGBUILDS (especially the ""s, IIRC), here a link to a pastebin
    My questions are: Are the jars to be put in /usr/share/java/jakarta-commons/$package/*.jar or plainly under jakarta-commons?
    Is it ok to delete all the docs, licenses + readmes?
    Sorry but it's very late now so I'll stop here and wait for your suggestions and tips, which will come hopefully..
    Greetings and good night,
    jakob

    Your absolutely right saying that never all commons packages would be used by just one program.
    I read the Java Packaging Guidelines again and it says that only commoly used and major libs should be sourced out to single packages. So the question is: Do any other packages in AUR or the official repos use some of the jakarta-commons projects so it would eventually pay to make single packages for them, or isn't it worth the hussle?
    I for my part now will leave the libs that are bundled with the package I wanted to upload at first in the package and use them.
    Thanks for your reply

  • Jakarta Commons - Using FileUpload

    Hello Java Experts!
    I'm trying to use the FileUpload feature from Jakarta Commons 1.2 and I'm having a real tough time uploading a file to an http server and then calling that file back so that the user can view their newly uploaded file. I'm able to store the file successfully if I point my file to "C:\Temp", however if I try to point the file to "http:\\mywebserver\temp" or to a network location (which I mounted) "\\mynetwork\myfolder\temp" I get an exception FileNotFoundException.
    I've searched the web and have not been able to find a resolution to this point. Any help would be greatly appreciated.
    Here is my code so far:
    DiskFileItemFactory fileUpload = new DiskFileItemFactory();
    fileUpload.setSizeThreshold(10485760);
    final String serverLocation = "http:" + "\\" + "\\webserver:8080\\temp");
    ServletFileUpload upload = new ServletFileUpload(fileUpload);
    // Set overall request size constraint
    // Max. 4 MB : 1 MB = 1048576 bytes
    upload.setSizeMax(4194305);
    List items = upload.parseRequest(request);
    Iterator iter = items.iterator();
    while (iter.hasNext())
    FileItem item = (FileItem) iter.next();
    if(item.getSize() > 0)
    File savedFile = new File(serverLocation + "test.tif");
    item.write(savedFile); // This does not work, the file is never written
    }

    You're getting this message when you try to compile the servlet, right? Make sure that jar file is in your classpath. Having it in Tomcat's classpath is fine for when Tomcat runs things but it has nothing to do with compiling.

  • Jakarta Commons FileUpload error : How should I go about it ?

    Hi fellas,
    I am using the Jakarta commons fileupload jar to write an upload servlet.
    I have created an html file where I upload a file as follows :
    <form name="upload_form" enctype="multipart-form/data" method="post" action="servlet/UploadServlet2">
    <center>
    <font face="tahoma" size="3">
    Please choose a file to upload <input type="file" name="upload_file">
    <hr>
    <input type="submit" name="bttn_submit" value="Upload File">
    </font>
    </center>
    </form>
    On posting this form, I am calling the UploadServlet which has the following code :
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.fileupload.*;
    public class UploadServlet2 extends HttpServlet
              protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
                   doWork(req, res);
              protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
                   doWork(req, res);
              private void doWork(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
                   PrintWriter out = res.getWriter();
                   out.println(req.toString());
                   out.println("page loading");
                   out.println(req.getContentType());
                   out.println(req.getParameter("myText"));
                   boolean isPart = FileUpload.isMultipartContent(req);
                   out.println(isPart);
                   if(isPart)
                        out.println("is multipart");
                        DiskFileUpload upload = new DiskFileUpload();
                        try
                             List items = upload.parseRequest(req);
                             Iterator it = items.iterator();
                             while(it.hasNext())
                                  FileItem item = (FileItem)it.next();
                                  if(!(item.isFormField()))
                                       out.println("success");
                        catch (FileUploadException e)
                             // TODO Auto-generated catch block
                             System.out.println(e.getMessage());
                             out.println(e.getMessage());
                   else
                        out.println("file not received");
                   out.flush();
                   out.close();
    But the output that I get is :
    org.apache.coyote.tomcat4.CoyoteRequestFacade@7244ca page loading application/x-www-form-urlencoded null false file not received
    WHATS THAT SUPPOSED 2 MEAN ?
    Where's the mistake in my code ?
    How should I remedy the situation ?
    Help needed immediately

    Hey thanx serlank,
    I never thought I could be sooooooooooo stupid...but u c, I have Java'd so much over the last 1 year that it's now become a headache 4 me 2 spot out such small mistakes.
    But thanx 2 people like u I never can drown in the Java Ocean. U're always there in the Search-and-Rescue team...
    Hope u'll always be there...
    Well ur ego glows again...
    Thanx alot 1ce again. It works now.
    Can I have ur mail Id if u don't mind ??

Maybe you are looking for

  • Content Conversion in sender channel

    Hi, I am having file to proxy scenario. Input file is a .txt file, which is having this type of data 111111   0000000  AAAAAAAA   BBBBBBBBBBBBBBBBBBBB 222222222222222   CCCCCCCCCCCC   1111111111111111111112222 I want to pick this file from FTP and pu

  • How do I take a date string, add "X" days to it, and display a new date?

    I have a date listed in a text string. I would like to convert it to a time stamp, and take a variable number of days, converted to seconds, added to the date, and displayed as a correct date. Example: 9/1/2011 adding 35 days is 10/6/2011. The trick

  • Apply a price list for user

    Dear All, is possible to apply prices lists for a specific user ? Giuseppe

  • Remapping the ctrl key

    hi, i am using LogMeIn Free for Mac to be able to remotely connect to my Mac from the outside world (typically from a PC). as i am starting to dabble in xcode, i have come across a problem: this utility doesnt seem to map the Control key. in the pref

  • I had to restore my iPod and now none of the songs want to play.

    I had to restore my iPod and now none of the songs want to play. I press play, it goes to the song screen, then around 5 seconds pass without the song starting and then it skips to the next song where the same thing happens. And that just keeps happe