如何使用 Vaadin 10 下载文件?
How to download a file with Vaadin 10?
我想让用户从服务器下载一个文件。
我 looked up 寻求解决方案并尝试举个例子 - 结果是这样的:
@Route("test-download")
public class Download extends VerticalLayout {
public Download() {
Anchor downloadLink = new Anchor(createResource(), "Download");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
}
private AbstractStreamResource createResource() {
return new StreamResource("/home/johny/my/important-file.log", this::createExportr);
}
private InputStream createExportr(){
return null;
}
}
当我在浏览器中转到该页面时,它给出了 java.lang.IllegalArgumentException: Resource file name parameter contains '/'
。
如何制作知道磁盘上文件位置的下载按钮(或锚点)?
看看 documentation, paragraph "Using StreamResource". The first parameter is just a file name that will be used by the browser to propose that file name to the user when downloading. So you could pass it like "important-file.log"
. The content of the download is provided by the InputStream
parameter. For instance, you could read from your file, see here:
File initialFile = new File("src/main/resources/sample.txt");
InputStream targetStream = new FileInputStream(initialFile);
我想让用户从服务器下载一个文件。 我 looked up 寻求解决方案并尝试举个例子 - 结果是这样的:
@Route("test-download")
public class Download extends VerticalLayout {
public Download() {
Anchor downloadLink = new Anchor(createResource(), "Download");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
}
private AbstractStreamResource createResource() {
return new StreamResource("/home/johny/my/important-file.log", this::createExportr);
}
private InputStream createExportr(){
return null;
}
}
当我在浏览器中转到该页面时,它给出了 java.lang.IllegalArgumentException: Resource file name parameter contains '/'
。
如何制作知道磁盘上文件位置的下载按钮(或锚点)?
看看 documentation, paragraph "Using StreamResource". The first parameter is just a file name that will be used by the browser to propose that file name to the user when downloading. So you could pass it like "important-file.log"
. The content of the download is provided by the InputStream
parameter. For instance, you could read from your file, see here:
File initialFile = new File("src/main/resources/sample.txt");
InputStream targetStream = new FileInputStream(initialFile);