如何在没有按钮的情况下在vaadin中启动文件下载?

raf*_*ael 13 vaadin vaadin7

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

谢谢拉斐尔

raf*_*ael 15

我自己找到了解决方案.其实两个.第一个使用不推荐使用的方法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);
}
}
Run Code Online (Sandbox Code Playgroud)

这里的javadoc 提到了一些内存和安全问题作为标记它被弃用的原因


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

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);
}
}
Run Code Online (Sandbox Code Playgroud)

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

  • 浏览器可能会阻止弹出窗口 (3认同)

小智 7

这是我的解决方法.它对我来说就像一个魅力.希望它会对你有所帮助.

  1. 创建一个按钮并通过Css隐藏它(不是代码:button.setInvisible(false))

    final Button downloadInvisibleButton = new Button();
    downloadInvisibleButton.setId("DownloadButtonId");
    downloadInvisibleButton.addStyleName("InvisibleButton");
    
    Run Code Online (Sandbox Code Playgroud)

    在您的主题中,添加此规则以隐藏downloadInvisibleButton:

    .InvisibleButton {
        display: none;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 当用户单击menuItem时:将其扩展fileDownloaderdownloadInvisibleButton,然后模拟downloadInvisibleButtonJavaScript 上的单击.

    menuBar.addItem("Download", new MenuBar.Command() {
      @Override
      public void menuSelected(MenuBar.MenuItem selectedItem) {
        FileDownloader fileDownloader = new FileDownloader(...);
        fileDownloader.extend(downloadInvisibleButton);
        //Simulate the click on downloadInvisibleButton by JavaScript
        Page.getCurrent().getJavaScript()
           .execute("document.getElementById('DownloadButtonId').click();");
      }
    });
    
    Run Code Online (Sandbox Code Playgroud)