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

Similar Messages

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

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

  • Question about Jakarta common fileUploader

    Hello!
    I want to be able to upload files to my databas through a jsp-page and have beeing recommended to use Jakarta common fileUploader.
    When extracting that file I saw that there was a lot of files, should all files be put in my WEB_INF/classes/"mypachage"-catalogue or?
    Thanks in advance!
    /D_S

    I am not sure what you mean. When you downloaded the commons-fileupload-1.0.zip there should be some JavaDoc files and a jar file (commons-fileupload-1.0.jar). You dont need to unzip the jar file. Just place it in WEB-INF/lib so the classes will be load. You'll also need to add the jar file to you classpath (or IDE classpath) so that you can compile.
    (Adjust the file names for what ever version you are using)

  • How should I go about this dispute

    Hello everyone,
    So recently I've been trying to get an auto loan and kept getting denied. Finally asked DCU what the problem was and they said I had a repo under Capital One that was still being reported. That was back in 2009, I got the vehicle back and paid it off.
    Called COAF today and they acknowledged the resolution of the account but that they could not change how it was reporting. They were trying to get me to file a dispute through them though I refused and said I could do it myself through the 3 agencies. Is there any reason they were so hard pressed for me to file disputes through them? How should I go about this.

    Moetylerm wrote:
    Hello everyone,
    So recently I've been trying to get an auto loan and kept getting denied. Finally asked DCU what the problem was and they said I had a repo under Capital One that was still being reported. That was back in 2009, I got the vehicle back and paid it off.
    Called COAF today and they acknowledged the resolution of the account but that they could not change how it was reporting. They were trying to get me to file a dispute through them though I refused and said I could do it myself through the 3 agencies. Is there any reason they were so hard pressed for me to file disputes through them? How should I go about this.If this isnt updating monthly I suggest you just leave it alone and find another lender willing to work with you. You would only dispute it if it has factual errors in the way its reporting. If you dispute it if its not updating monthly when it updates after the dispute its going to cause a Fico score drop. If it is updating monthly now then you still would only dispute errors that are reporting but it wouldnt drop your Fico score anymore. DCU doesnt like other things they see in your CR is what I suspect since this actually is a redeemed repo and not one left unpaid.

  • Hi, I have a macbook pro 10.6.8 and an iphone 4s. I have already created an icloud account. I want my normal mails to be saved on icloud. how should i go about?

    Hi, I have a macbook pro 10.6.8 and an iphone 4s. I have already created an icloud account. I want my normal mails to be saved on icloud. how should i go about?

    I'm not sure I understand your question really, but one thing for sure is that you need Lion for iCloud to work.

  • TS2755 I need to get hold of old messages from a previous IPhone.  How should I go about that?

    I need to get hold of old meesges   about 17 months from a previous IPhone.  How should I go about that ?

    Well, you wouldn't....
    I presume you don't have the old phone? Also, that you are talking about text or iMessages? They wouldn't be saved anywhere if that is what you were looking for.
    Cheers,
    GB

  • HT1338 I have 10.5.8 at present I want to update the software. How should I go about it?

    I have 10.5.8 at present I want to update the software. How should I go about it?

    Welcome to Apple Support Communities
    http://support.apple.com/kb/sp575 If the Mac is compatible, call Apple to buy Snow Leopard. Insert the disc and upgrade Mac OS X. Then, go to  > Software Update.
    http://www.apple.com/osx/specs If your Mac is supported, open App Store and purchase OS X Mountain Lion. See if your programs are supported > http://www.roaringapps.com

  • TS4148 I forgotten my iphone password and tried many times keying in wrong password. Now my iphone is disabled. How should I go about restoring back my iphone back to normal. Thank you for your assistance. Eileen Poh

    TO: CUSTOMER SERVICE SUPPORT PERSONNEL
    I forgotten my iphone password and tried many times keying in wrong password. Now my iphone is disabled. How should I go about restoring back my iphone back to normal.
    Thank you for your assistance.
    Eileen Poh
    <Email Edited by Host>

    Connect to itunes and click the restore button and restore from your backup.

  • I've signed up for a Students Single App Plan but I want to upgrade to a Students Complete plan, can/how should I go about this?

    I've signed up for a Students Single App Plan but I want to upgrade to a Students Complete plan, can/how should I go about this?
    It prompts me to upgrade to the complete plan, but not the complete students plan.

    I think you need Adobe contact information - http://helpx.adobe.com/contact.html

  • Just bought a new laptop,how should I go about syncing new computer to my I pad2 or vice versa

    Just bought a new laptop,how should I go about syncing my I pad2 to new computer,I also
    Have Apple tv,should I download I-Tunes to new computer,then sync I pad?will content of Ipad
    Auto load to new pc?   Thanks

    I would begin by migrating my user files from the old computer to the new computer.

  • File size with Jakarta Commons FileUpload

    Hello fella experts,
    I am using the org.apache.commons.FileUpload package to upload a file via a servlet.
    I'm implementing the DiskFileUpload() method in the servlet.
    My problem is that I want to apply a file-size validation and specify that files with size greater than 1MB should not be uploaded.
    How to accomplish this ?
    Any suggessions ?
    Thanx in advance.

    Hi, I'm trying this code, and it works pretty fine, but when I try to transfer a .zip file, it give me a .zip file that I can't extract.
    Please.. Am I doing something wrong, do I miss something??
    I set already the File Type to binary...
    any comments..
    public static void copyFiles(String server, String user, String pwd, String origen, String destino)
    try {
    FTPClient ftp = new FTPClient();
    ftp.connect(server);
    ftp.login(user,pwd);
    ftp.setFileType(ftp.BINARY_FILE_TYPE);     
    //ftp.enterLocalPassiveMode();
    ftp.changeWorkingDirectory(origen);
    int reply = ftp.getReplyCode();
    if(!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    FTPFile[] files = ftp.listFiles();
    FTPFile ftpfile = null;
    OutputStream output = null;
    for (int i = 0; i < files.length; i++) {
    ftpfile = files;
    if (ftpfile.isFile()){
    output = new FileOutputStream(new File(destino+ftpfile.getName()));
    if (ftp.retrieveFile(ftpfile.getName(),output)){
    output.close();
    ftp.logout();
    ftp.disconnect();
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("Error : " + e.toString());

  • Jakarta commons FileUpload - ServletFileUpload.parseRequest(...)

    Hello people. I am using:
    # Orion app server (don't ask why)
    # WebWork 2.1.7 framework
    # Jakarta commons file upload 1.2
    While writing a file upload action I am having problems with ServletFileUpload.parseRequest(...) as it always returns an empty list.
    Reading related Jakarta FAQ it says "this most commonly happens when the request has already been parsed, or processed in some other way."
    I then assumed it was my WebWork interceptor so I took that out but I'm still getting the same problem.
    Am I missing something in my JSP, another <input> or something?
    Is the request being parsed somehwere else beforehand (maybe a WebWork issue)?
    Any help would be much appreciated.
    Here is the relevant code...
    My JSP<html>
         <head>
              <title>File Upload</title>
         </head>
         <body>
              <form enctype="multipart/form-data" method="post" action="doUpload.action" name="uploadForm">
                   <input name="upload" type="file" label="File"/>
                   <input type="submit" value="upload" />
              </form>
         </body>
    </html>
    The execute() method of my action     public String execute() {
              log.info("executing");
              // get the request
              HttpServletRequest request = ServletActionContext.getRequest();
              // check that we have a file upload request
              boolean isMultipart = ServletFileUpload.isMultipartContent(request);
              log.debug("request "+ ( (isMultipart ? "IS" : "is NOT") ) +" a multi-part");
              if (isMultipart) {
                   // Create a factory for disk-based file items
                   DiskFileItemFactory factory = new DiskFileItemFactory();
                   factory.setSizeThreshold(100);
                   factory.setRepository(new File("C:/tmp/cms/uploads"));
                   // Create a new file upload handler
                   ServletFileUpload upload = new ServletFileUpload(factory);
                   // Parse the request
                   try {
                        //List /* FileItem */ items = upload.parseRequest(request);
                        _uploads = upload.parseRequest(request);
                   } catch (FileUploadException e) {
                        log.error("Error parsing request" , e);
                   // if the above method doesn't work, use my method :)
                   if (_uploads.isEmpty()) {
                        _uploads = parseRequest(request);
              return (_uploads == null) || _uploads.isEmpty() ? INPUT : SUCCESS;
         }My implementation of parseRequest(...) works but returns File objects and I need FileItem objects. I don't really want to use this method but will include it here just incase it triggers some inspiration for someone.
    private List<File> parseRequest(HttpServletRequest requestObj) {
             List<File> files = new ArrayList<File>();
             // if the request is a multi-part
             if (requestObj instanceof MultiPartRequestWrapper) {
                  // cast to multi-part request
                  MultiPartRequestWrapper request = (MultiPartRequestWrapper) requestObj;
                   // get file parameter names
                   Enumeration paramNames = request.getFileParameterNames();
                   if (paramNames != null) {
                        // for each parameter name, get corresponding File
                        while (paramNames.hasMoreElements()) {
                             File[] f = request.getFiles("" + paramNames.nextElement() );
                             // add the File to our list
                             if (!ArrayUtils.isEmpty(f)) {
                                  files.add(f[0]);
              return files.isEmpty() ? null : files;
        }

    Hi edin7976, just wonder have you got any feedback for this problem?
    I really want to push this thread up as I am stuck at the exact same question. Can anybody give a hint?

  • How should I go about getting my iPhone headphone jack repaired?

    So recently my headphone jack has been playing up, where it ends up with loads of static and the vocals are oddly quiet and echoey, but it seems to correct itself if I jiggle the jack around a little, which obviously must be damaging, so I've stopped doing it. I bought the phone from Carphone Warehouse in September and was wondering how I can go about getting this fixed? I didn't take out any apple care or anything, but surely I'm still covered by some sort of warranty? If not, how much will Apple charge for this to be repaired/replaced?

    The warranty is 1 year. If it's less than a year old, and there are no visible signs of damage, then it should be covered under warranty. If it is more than a year old, then you should be able to get an out of warranty replacement from Apple ($149 in the U.S. You'll have to check on the price in the UK).
    Make an appointment at the genius bar at your local Apple Store.

  • How should I go about doing this exercise (networking/database related)

    Hey everyone
    As a learning exercise for myself, I've decided to write a basic web based chat room application. I'm going to:
    -allow users to create an account (store this info in a database)
    -force users to log in before entering a lobby (there will be multiple lobbies)
    -have users join a lobby, and then select one chatroom to join in that lobby
    -allow multiple users in each lobby and chatroom
    It is also going to be web based, so I want a user to be able to open a web page and then use the application without having to download/install it.
    My question is: How should I begin this project? As I can see it, I have a bunch of options, including using an applet or using java web start. What are my other options (if any)? What are the advantages/disadvantages of these options, and which would you use if you were creating a chatroom for a website that had hired you?
    Thanks for your help

    nightmares wrote:
    As a learning exercise for myself, I've decided to write a basic web based chat room application. I'm going to:
    -allow users to create an account (store this info in a database)
    -force users to log in before entering a lobby (there will be multiple lobbies)
    -have users join a lobby, and then select one chatroom to join in that lobby
    -allow multiple users in each lobby and chatroom
    It is also going to be web based, so I want a user to be able to open a web page and then use the application without having to download/install it.First of all, you haven't picked a trivial project ... but I bet you'll be a lot better by the time you've finished it.
    You've made a decent start by identifying some of the major functions that your chat room will support. You'll probably need to expand on it, and also determine the exact information requirements for those modules (For example: what will an account look like? What data will it hold? How will it interact with the other modules/classes in the chat room? What does your Lobby need to do?).
    I'm not an expert in web-based programming, but there are a few "unversals" to good design that might help (and provide you with some things to Google). It's probably going to sound like CD-101, but here goes:
    1. Pick a good development platform - You could do this with Notepad; but I don't advise it. You're going to have to manage a lot of complexity, and IDEs are the way to go. I don't want to start a war here, but both NetBeans and Eclipse have the tools for this sort of project - and they're free.
    2. Think what+, not how+ - ...at least to begin with :-). This is probably the hardest thing for newbies to learn, because they're just dying to get started on the code. Decide what you want to do before you dive into the how. You may find you change your mind about the how before you come to code. You may also find that somebody's already written a piece of code or library to do just what you want. As a very simple example: sendMessage() is a 'what' method; openSocket() is the 'how'.
    3. Loose coupling - as far as possible, keep your methods and classes self-contained and well-focused. This general principle also applies to system components - try to make sure that each one is well-defined and "talks" to other components in a well specified manner. There are several design patterns for the type of thing you want to do, but you might want to start with MVC (Model/View/Control). It'll also help you when you want to test (see below).
    4. Good naming - '*i*' may be a perfectly good name in a 'for' loop, but it's pretty useless outside it. Make your variable and method names mean something. There are also several conventions that other Java programmers expect, so you might want to [start here.|http://java.sun.com/docs/codeconv/]
    4. Think big, but start small - For example, a good 'test of concept' might be to get your chat room running on your local machine using a local database first. Providing you're using all the middleware you'll be using for your 'finished' version (eg, Tomcat), porting to the Internet shouldn't be too onorous (but it's unlikely to be completely glitch-free).
    5. Test, test, test - Test everything you do. It sounds boring, but good testing can actually highlight design problems. Find out a bit about it (eg, smoke tests, boundary checks) and try and find a tool that fits your needs. [This page|http://java-source.net/open-source/web-testing-tools] has a few suggestions.
    6. Document - Another snorer, but vital. javadoc is your friend, but you'll probably want other forms of documentation as well. UML wouldn't be a bad place to start.
    7. And finally, read - there's a lot to know about this stuff, and it's changing all the time. Here's a few pointers to get you going:
    - Database comms/Persistence/Model - JPA, Hibernate, JDBC.
    - Databases - MySQL, Derby, Oracle, DB2, SQLServer; also some [others here.|http://java-source.net/open-source/database-engines]
    - View - JSP, Struts, Ajax, Swing (non-web)
    - Control - Servlets, EJB, Tomcat, Jetty
    - Testing - JUnit
    - Communication/Messaging - JMS, SOAP
    - Other: ant, jar, war, ear, xml
    If you have any mates in the biz, you might want to talk to them too. An ounce of experience is worth a pound of heartache.
    HIH
    Winston
    Edited by: YoungWinston on Jul 30, 2009 3:33 AM

Maybe you are looking for

  • OB52 authorisation group (close&open posting periods only for partic users

    Dear FI-CO Guru's In ob52- I want open postin periods 1)Certain group of user will allow for posting only normal periods and 2) Certain group of users will allow for posting normal and special periods this is our business requirement kindly suggest h

  • Disable G/L account field in Shopping cart screen

    Hi SDN, I am ABAP Developer and new to the SRM system, I got a requirement to disable G/L account field in the Shopping cart creation screen and overview screen and also I have to disable  the message that is triggered when the G/L account field not

  • Restore pages to ipad mini

    I accidentally deleted the "Information/Help/Gettting Started" section from my Pages app on ipad mini.  How do I get this back.  (I cannot believe it let me delete this important information).

  • Custom Infotype not displaying locked records in the list screen (3000)

    I have a custom infotype (9xxx) that will not display the locked records (locked indicator (sprps) is set to X) in the list screen (3000) in PA20 and PA30. Any ideas on what may be causing the records to not display in the list screen? Thanks, Ted

  • J2EE Installation problems

    I am having trouble getting my system to complie Servlets and to recognize JSP pages. I installed the J2EE, following the instruction set forth on Sun's site, but when I attempt to compile a servlet, it says that the javax.servlet.*; is not found. I