Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT - uploading file to server without using FileUpload dialog

Tags:

gwt

I have a requirement to upload a file to server from the web application written in GWT. The complex part is that FileUpload dialog box cannot be dislayed (due to space crunch issue on TabPanel). So on click of a button, I need to:

  • Open the file selection directly, without bothering the user with an additional Form containing an UploadItem to click
  • Start the upload immediately after file selection

I have written following code in GWT to open file select dialog box on click of button:

final FileUpload upload = new FileUpload(); 
    
upload.setVisible(false);
upload.setName("uploadFormElement"); 
panel.add(upload);
    
panel.add(new Button("Select File", new ClickListener() { 
    public void onClick(Widget pSender) { 
         jsClickUpload( upload.getElement() );
         MessageBox.showMessage("selected filename: " + upload.getFilename());
    } 
}));
    
native void jsClickUpload(Element pElement) /*-{ pElement.click(); }-*/;

Although this does open the file select dialog on the button click, it simultaneously also shows the message box with blank value for file name.

So what I need is that only after file is selected, the message box is displayed. How can I do this? Also, how to upload the actual file to Server after this (M

like image 879
Aditya G. Avatar asked Oct 22 '12 14:10

Aditya G.


1 Answers

Here is a working example:

public void onModuleLoad() {
    final FileUpload upload = new FileUpload();
 
    upload.setVisible(false);
    upload.setName("uploadFormElement");
    RootPanel.get().add(upload);

    Button b = new Button("Select File");
    b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            jsClickUpload(upload.getElement());
        }
    });
    
    upload.addChangeHandler(new ChangeHandler() {
       @Override
        public void onChange(ChangeEvent event) {
            Window.alert(upload.getFilename());
        }
    });
    
    RootPanel.get().add(b);
}

native void jsClickUpload(Element pElement) /*-{
    pElement.click();
}-*/;

To upload it you need a Servlet receiving the upload. I use this additional library: http://code.google.com/p/gwtupload/ You find all the code needed on their website.

like image 196
tommueller Avatar answered Sep 21 '22 08:09

tommueller