问题
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