本文介绍了如何使用Vaadin 10下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户从服务器下载文件.我查找了解决方案并尝试举一个例子-最终结果是:

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;
    }
}

当我在浏览器中转到页面时,给出java.lang.IllegalArgumentException: Resource file name parameter contains '/'.
如何使下载按钮(或锚点)知道磁盘上的文件位置?

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?

推荐答案

看看文档,使用StreamResource"段落.第一个参数只是文件名,浏览器将使用该文件名在下载时向用户建议该文件名.因此,您可以像"important-file.log"一样传递它.下载的内容由InputStream参数提供.例如,您可以从文件中读取内容,请参见此处:

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);

这篇关于如何使用Vaadin 10下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 20:55