如何解决Vaadin 14 在 Button Click 上下载文件不起作用
我正在使用 https://vaadin.com/directory/component/file-download-wrapper 用下面的代码
exportButton = new Button("export"));
FileDownloadWrapper buttonWrapper = new FileDownloadWrapper(
new StreamResource(genericGridView.getExportFileCaption(),() -> getExportStream()));
buttonWrapper.wrapComponent(exportButton);
buttonLayout.add(exportButton); //Button Layout is an Horizontal Layout which is added finally in the
main Layout.
而这部分代码是在我的视图加载时编写的。但是 getExportStream 方法在视图加载和按钮点击事件中都没有被执行(试图在 Eclipse 中进行调试,但它从未执行过)。
请您帮忙执行此操作,是否我在这里做错了什么?
解决方法
您需要将 FileDownloadWrapper 添加到布局而不是 Button。否则,FileDownloadWrapper 什么也不做。
,对我来说,使用 FileDownloadWrapper
的代码看起来是正确的。所以我倾向于认为问题更多地与你如何生成数据有关。我从我的测试应用程序中复制了一个有效的代码片段。此处的 CSV 导出使用 StatefulBeanToCsv
库中的 StatefulBeanToCsvBuilder
和 com.opencsv.opencsv
。
private void export(Grid<Person> grid,TextArea result) {
Set<Person> selection = grid.asMultiSelect().getValue();
Stream<Person> persons = persons = selection.stream();
StringWriter output = new StringWriter();
StatefulBeanToCsv<Person> writer = new StatefulBeanToCsvBuilder<Person>(
output).build();
try {
writer.write(persons);
} catch (CsvDataTypeMismatchException
| CsvRequiredFieldEmptyException e) {
output.write("An error occured during writing: " + e.getMessage());
}
result.setValue(output.toString());
StreamResource resource = new StreamResource("export.csv",() -> new ByteArrayInputStream(output.toString().getBytes()));
FileDownloadWrapper download = new FileDownloadWrapper(resource);
Button button = new Button("Click to download");
download.wrapComponent(button);
add(download);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。