javafile-uploadstruts-1

Java - Commons-fileupload.jar - Problem


I am trying to upload a file using commons-fileupload-1.1.1.jar file (I know it is not the latest version but it comes with struts 1.3.10 so I am using the same).

Now the problem is when I parse the request (HttpServletRequest) to get a List of FileItems, I am getting an empty list.

        DiskFileItemFactory factory = new DiskFileItemFactory();

        File tempDir = new File("/fileUploadDirectory");
        tempDir.mkdir();

        // Set factory constraints
        factory.setSizeThreshold(10000);
        factory.setRepository(tempDir);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(10000);

        // Parse the request
        List items = upload.parseRequest(request);
        System.out.println(items);

        System.out.println(request.getContentLength());

        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                System.out.println("File is a FormField");
            } else {
                System.out.println("File is a File");
            }
        } 

Q1. Why I am getting an empty list?

When I am printing the size of the request by request.getContentLength() (as shown above in the code), I get some numerical data (1536) which I think is showing the length of the file. If it is showing the length of the file, then why I am not getting list of FileItems?

Note: I am using it with Struts 1.3.10 with ActionForm. Is is creating any problem.

Note: I am also not getting any exception while parsing the request.


Solution

  • If the list is empty, then the request was most likely not send as multipart/form-data. Ensure that the request method is set to post and that encoding type is set to multipart/form-data:

    <form method="post" enctype="multipart/form-data">
    

    (just substitute the HTML <form> element with the Struts equivalent, which is likely <html:form>)

    That said, why don't you make use of the Struts builtin file upload component? Googling learns me that there's a <html:file> component which needs to be tied with a org.apache.struts.upload.FormFile property.