How to download a file with Vaadin 10?

2019-08-07 12:07发布

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条回答
Luminary・发光体
2楼-- · 2019-08-07 12:27

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);
查看更多
登录 后发表回答