Search code examples
javafiledownloadanchorvaadin14

Is there a way to call an anchor after a Context Menu Item is clicked?


Im trying to download a file using the anchor and a context menu. I need to create the anchor dynamically, so that means I need to call a function, before the anchor gets called.

I already tried the following:

this.ctmFilesGrid.addItem("  Download", click -> {
            if(click.getItem().isPresent()) {
                this.fDownloadingFile = click.getItem().get();
                this.createDownloadingAnchor(); 
                this.ancFileDownloader.getElement().callJsFunction("click");
            }
        }).addComponentAsFirst(FontAwesome.Solid.FILE_DOWNLOAD.create());

But the anchor isnt called.

I hope someone can help me with that. Thanks in advance


Solution

  • You can't start a download from a server-side event listener, no. The browser will block this; it's a security limitation. This is because there's no way to link the "click" function call to the original user event, and all downloads must be directly initiated by the user.

    The proper solution would probably be something like a custom Servlet or a RequestHandler that handles the generation of the content. Do also check https://vaadin.com/directory/component/lazy-download-button for ideas.