Problem with making download buttons

Hi, I’m trying to create some download buttons in a Vaadin application. They work but when clicking fast I get connection errors and have to restart the application. I reproduced the problem in a small test app:


import com.vaadin.Application;
import com.vaadin.terminal.StreamResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Window;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class MyVaadinApplication extends Application {
    private Window window;

    @Override
    public void init() {
        window = new Window("My Vaadin Application");
        setMainWindow(window);
        Button button = new Button("Download");
        button.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {}
				StreamResource stream = new StreamResource(new StreamResource.StreamSource() {
					public InputStream getStream() {
						return new ByteArrayInputStream("text".getBytes());
					}
				}, "file", MyVaadinApplication.this);
				window.open(stream);
            }
        });
        window.addComponent(button);
    }
}

Is there a workaround for this problem, am I doing something wrong?

I’m not 100% sure but i’m guessing that’s what happens:

You click on the button–>The streamresource gets created–> window.open gets called which causes the page to load the resource

While this is happening you’re repeatedly pressing the button.

I’m thinking now that the page ones is already trying to load the resource and because of that is not able to send the button-click request to the server anymore. Or the server can’t compute them.
(Disclaimer: I’m not an expert in that regard so correct me if i’m wrong)

I found a solution, adding the windowName parameter with value “_new” or “_blank” to the Window.open method call fixes the problem :slight_smile:

Ok so i think it was really what i thought what happened. When you don’t add these parameter the browser will try to open the resource in the same window/tab but if you add them it will open a new window/tab. This way the UI with the Button is still active in the browser.

Another way to solve the issue but still open the resource in the same window (if for some reason you really want that it will direct you away from your app) would be to disable the button as soon as you click it.

The thing is, even without that parameter the file was being downloaded without leaving the application and the button works fine if you don’t click it very fast, that’s what made this situation unclear to me. DisableOnClick would also work but only when using one button and I needed more of them. Anyway it’s solved now :slight_smile: