Search code examples
file-uploadgwt

GWT - Upload and get files uploaded with FileUpload


I'm using FileUpload class for uploading multiple files. Since i do not have the choice to use a library (like gwt-upload or others), I created the class MultiFileUpload :

public class MultiFileUpload extends FileUpload {
    public MultiFileUpload() {
        this.getElement().setAttribute("multiple", "multiple");
        this.setTitle("Select files");
    }
}

I added it to my pannel and can select multiple files successfuly :

private MultiFileUpload upload = new MultiFileUpload();
upload.getElement().setId("files");
grid.setWidget(2, 1, upload);

My problem is: I cannot get the path of each file for sending it to another service (from another module created with Jave Entreprise Edition aka jee, where I should use paths).

What I tried

  • Getting files from FileUpload
upload.getElement.getgetChildCount(); ==> equal 0
upload.getFileName(); ==> null
  • I tried using js:
private static native boolean validateFiles() /*-{
        var filesCount = $wnd.$('input:file')[0].files.length;
        for(i = 0; i<filesCount; i++){
        console.log($wnd.$('input:file')[0].files[i].path) //==> path is undefined
        }
}-*/;
  • Using DOM:
Element e =  DOM.getElementById("files");
e.getgetChildCount(); ==> equal 0

Any help is much appreciated.


Solution

  • Solution: I send files and all form data in a POST request to the servlet:

    form.setAction(UPLOAD_ACTION_URL);
    form.setEncoding(FormPanel.ENCODING_MULTIPART);
    form.setMethod(FormPanel.METHOD_POST);
    

    Then in my servlet, i get files path from the request:

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);
    
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    File uploadedFile = new File(fileName);
                    item.write(uploadedFile);
                  }
    }