GWT - upload a file to the server without using the FileUpload dialog

I have a requirement to upload a file to the server from a web application written in GWT. The tricky part is that the FileUpload dialog cannot be unloaded (due to the problem of running out of space on the TabPanel). Therefore, when I click the button, I need:

  • Open the file selection directly without bothering the user with an additional form containing the UploadItem file to click
  • Start the download immediately after selecting the file

I wrote the following code in GWT to open a file selection dialog when a button is clicked:

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 opens a file selection dialog when a button is pressed, it also also displays a message box with an empty value for the file name.

So, I need that only after selecting the file a message box will be displayed. How can i do this? Also, how to upload the actual file to the server after that (M

+6
source share
1 answer

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 download it, you need the servlet receiving the download. I use this additional library: http://code.google.com/p/gwtupload/ You will find all the code needed on their website.

+8
source

All Articles