我有以下代码从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);
}
});
下载找到我要下载的文件。如果我从 Chrome 单击按钮,浏览器会下载我的文件,如果我从 Firefox 单击按钮,则没有任何反应。我需要以什么方式调整我的代码以支持Chrome和Firefox?
我使用本教程作为参考。
对于
由Vaadin Flow中的某些操作触发的下载,还有一个解决方法,例如,您有一个按钮,可以在下载文件之前有条件地显示一个对话框:
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();");
在FF,Chrome和Edge中进行了测试。解决方法模拟单击触发下载的定位点。