如何在没有按钮的情况下在

如何在没有按钮的情况下在

本文介绍了如何在没有按钮的情况下在 vaadin 中开始文件下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道创建一个 FileDownloader 并使用 Button 调用扩展真的很容易.但是如何在没有 Button 的情况下开始下载?
在我现在的特定情况下,我有一个 ComboBox 并且我想发送给用户的文件是在根据输入更改其值后生成的.该文件应立即发送,无需等待再次单击.这很容易吗?

I know that it is really easy to create a FileDownloader and call extend with a Button. But how do I start a download without the Button?
In my specific situation right now I have a ComboBox and the file I'd like to send to the user is generated after changing its value, based on the input. The file should be sent immediately without waiting for another click. Is that easily possible?

谢谢拉斐尔

推荐答案

我自己找到了解决方案.其实两个.第一个使用已弃用的方法 Page.open()

I found a solution myself. Actually two.The first one uses the deprecated method Page.open()

public class DownloadComponent extends CustomComponent implements ValueChangeListener {
private ComboBox cb = new ComboBox();

public DownloadComponent() {
    cb.addValueChangeListener(this);
    cb.setNewItemsAllowed(true);
    cb.setImmediate(true);
    cb.setNullSelectionAllowed(false);
    setCompositionRoot(cb);
}

@Override
public void valueChange(ValueChangeEvent event) {
    String val = (String) event.getProperty().getValue();
    FileResource res = new FileResource(new File(val));
    Page.getCurrent().open(res, null, false);
}
}

javadoc 此处 提到一些内存和安全问题作为将其标记为弃用的原因

The javadoc here mentions some memory and security problems as reason for marking it deprecated

在第二个中,我尝试通过在 DownloadComponent 中注册资源来绕过这个已弃用的方法.如果 vaadin 专家对此解决方案发表评论,我会很高兴.

In the second I try to go around this deprecated method by registering the resource in the DownloadComponent. I'd be glad if a vaadin expert comments this solution.

public class DownloadComponent extends CustomComponent implements ValueChangeListener {
private ComboBox cb = new ComboBox();
private static final String MYKEY = "download";

public DownloadComponent() {
    cb.addValueChangeListener(this);
    cb.setNewItemsAllowed(true);
    cb.setImmediate(true);
    cb.setNullSelectionAllowed(false);
    setCompositionRoot(cb);
}

@Override
public void valueChange(ValueChangeEvent event) {
    String val = (String) event.getProperty().getValue();
    FileResource res = new FileResource(new File(val));
    setResource(MYKEY, res);
    ResourceReference rr = ResourceReference.create(res, this, MYKEY);
    Page.getCurrent().open(rr.getURL(), null);
}
}

注意:我真的不允许用户打开我在服务器上的所有文件,你也不应该这样做.仅供演示.

Note: I do not really allow the user to open all my files on the server and you should not do that either. It is just for demonstration.

这篇关于如何在没有按钮的情况下在 vaadin 中开始文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:59