Vaadin Flow download code works for Chrome but not for Firefox - How can I support both?

匆匆过客 提交于 2019-12-25 01:13:26

问题


I have the following code to download a file from Vaadin Flow (12.0.7).

exportBtn.addClickListener(e -> {
toDownload = FileUtil.getLatestExport();

(toDownload != null) {
                StreamResource resource = new StreamResource(toDownload.getName(),
                        () -> FileUtil.getInputStreamForFile(toDownload));

                Element object = new Element("object");
                object.setAttribute("download", true);
                object.setAttribute("data", resource);

                Input name = new Input();
                UI.getCurrent().getElement().appendChild(name.getElement(), object);
   }
});

toDownload locates the file which I want to download. If I click the button from Chrome the browser downloads my file if I click the button from Firefox nothing happens. In what way do I need to adjust my code to support Chrome and Firefox?

I used this tutorial as reference.


回答1:


There is also a workaround for downloads triggered by some action in Vaadin Flow, e.g. you have a button that conditionally shows a dialog before downloading the file:

 Anchor hiddenDownloadLink = new Anchor(createYourStreamResource(), "Workaround");
 hiddenDownloadLink.setId("DownloadLinkWorkaround_" + System.currentTimeMillis());
 hiddenDownloadLink.getElement().setAttribute("style", "display: none");
 // TODO: add the link somehwere in your view
 UI.getCurrent().getPage().executeJs("document.getElementById('" + hiddenDownloadLink.getId().orElseThrow() + "').click();");

Tested in FF, Chrome and Edge. The workaround simulates a click on an anchor that triggers the download.



来源:https://stackoverflow.com/questions/56567121/vaadin-flow-download-code-works-for-chrome-but-not-for-firefox-how-can-i-suppo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!