如何模拟vadin流中锚标记的点击事件?



我可以使用上传组件从页面上传文件到我的文件系统,如下所示。

return (MultiFileReceiver) (String fileName, String mimeType) -> {
try {
File file = new File(uploadFileDirectory,fileName);
return fileOutputHandlerService.fileOutput(file);
} catch (Exception e) {
throw new RuntimeException(e);
}
};

但是当涉及到用给定路径下载文件时,我无法完成。唯一的解释是使用锚元素。但是我想使用ContextMenu组件来触发下载。我有一个上下文菜单组件派生自一个网格

fileListContext = grid.addContextMenu();
fileListContext.addItem("Download",uiListener.fileDownloadRequestListener());

我实现了上下文菜单监听器,如下所示。我想点击上下文菜单弹出并提示浏览器打开保存位置供用户开始下载。

private  ComponentEventListener <GridContextMenu.GridContextMenuItemClickEvent<FileEntity>>  fileDownloadRequestListener(){
//created stream user and anchor element. how to trigger download attribute of anchor?
return selectedFile-> {
StreamResource resource = new StreamResource(selectedFile.getItem().get().getFileName(),
()->fileInputHandlerService.fileInput(selectedFile.getItem().get()));
anchor = new Anchor(resource,"a");
anchor.getElement().setAttribute("download",true);
anchor.setVisible(true);
add(anchor);
};
}

调整你的fileDownloadRequestListener,它应该工作:

private ComponentEventListener<GridContextMenu.GridContextMenuItemClickEvent<FileEntity>> fileDownloadRequestListener() {
return selectedFile -> {
StreamResource resource = new StreamResource(selectedFile.getItem().get().getFileName(),
() -> fileInputHandlerService.fileInput(selectedFile.getItem().get()));
anchor = new Anchor(resource, "a");
Element element = anchor.getElement();
element.setAttribute("download", true);
// Hide the anchor from the user
element.getStyle().set("display", "none");
add(anchor);
// Trigger click and remove when ready
element.executeJs("return new Promise(resolve =>{this.click(); setTimeout(() => resolve(true), 150)})", element).then(jsonValue -> remove(anchor));
}
Anchor download = new Anchor();
download.add(downloadButton);
download.getElement().setAttribute("download", "Hscodelistdownload.xlsx");
downloadButton.addClickListener(e -> {

StreamResource resource = new StreamResource("Hscodelistdownload"+System.currentTimeMillis()+".xlsx", Exporter.exportAsExcel(grid));
download.setHref(resource);
Element element = download.getElement();
element.setAttribute("download", true);
element.getStyle().set("display", "none");
element.executeJs("return new Promise(resolve =>{this.click(); setTimeout(() => resolve(true), 150)})", element).then(jsonValue -> remove(download));
StreamRegistration regn = VaadinSession.getCurrent().getResourceRegistry().registerResource(resource);
UI.getCurrent().getPage().open(regn.getResourceUri().toString());

});
add(downloadButton);

最新更新