How to download a file with Vaadin 10?

拈花ヽ惹草 提交于 2019-12-11 09:29:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!