Stephane Grenier Stephane Grenier - 23 days ago 9
Java Question

Vaadin FileDownload requires the button be clicked twice to download

I'm following the Vaadin sample code but when I do I require a second click to start the file download. Below is my code:

final StreamResource streamResource = new StreamResource(
() -> {
return new ByteArrayInputStream("hello world".getBytes());
}, document.getName() + ".txt");

FileDownloader fileDownloader = new FileDownloader(streamResource);
fileDownloader.extend(getDownloadButton());


There's nothing special about the code to create the button but as requested in the comments here it is:

Button downloadButton = new Button("Download");

Answer Source

Although I don't like this solution it works. It has to do with how the download works and some restrictions by the browser. I'm sure there's a better solution but right now I simulate the first click with Javascript. If someone can find the correct answer then please post it and I'll change the selected answer, otherwise this is the only solution I found (posted in the Vaadin forums).

streamResource = createStreamResource();
downloadButton createDownloadButton();
downloadButton.setId("DownloadButtonID");

if(fileDownloader == null)
{
    fileDownloader = new FileDownloader(streamResource);
    fileDownloader.extend(downloadButton);
    // Javascript click so that it works without a second click
    Page.getCurrent().getJavaScript().execute(
           "document.getElementById('DownloadButtonID').click();");
} else {
    fileDownloader.setFileDownloadResource(streamResource);
}