Download button in Vaadin 24.9

So we have DownloadHandler since 24.8, but how do I hook it up with a button? All examples I found use Anchors.
Are there still some weird tricks required, or did I only miss the simple way?

DownloadHandler is all about how requests are handled - it doesn’t change how requests are sent. All the same old tricks still apply there.

Follow Support triggering a file download when clicking a button · Issue #7203 · vaadin/flow-components · GitHub for updates related to sending those requests.

Hi Gunnar,

it’s not that different: you define the anchor with the new download handler stuff (which is BTW much easier than before) and then add a Button to the anchor. Hence the button becomes the visible face of the anchor like so:

Anchor anchor = new Anchor(
  DownloadHandler.fromInputStream((event) -> {
    try {
      return new DownloadResponse(byte [] content, String filename, String mimeType, int length);
    } catch (Exception e) {
      return DownloadResponse.error(500);
    }
  }), "");
Button button = new Button("Export", VaadinIcon.FILE_TABLE.create());
anchor.addComponentAsFirst(exportButton);

Thanks a lot, guys.
Nevertheless, I’m looking forward to the day when this Button/Anchor wrapper thing becomes obsolete. :)

1 Like

I would like to add:


Button button = new Button("Export", VaadinIcon.FILE_TABLE.create());
button.setTabIndex(-1);
button.getElement().setAttribute("role", "presentation");
anchor.addComponentAsFirst(exportButton);