问题
I want to let user to download a file from server. I looked up for the solution and when trying to make an example - ended up with this:
@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;
}
}
Which is giving java.lang.IllegalArgumentException: Resource file name parameter contains '/'
when I go to the page in browser.
How do I make a download button (or anchor) knowing file location on disk?
回答1:
Have a look at the 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);
来源:https://stackoverflow.com/questions/52150056/how-to-download-a-file-with-vaadin-10