How to start a file download in vaadin without button?

后端 未结 2 1923
我在风中等你
我在风中等你 2021-02-04 09:21

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?

2条回答
  •  天命终不由人
    2021-02-04 09:58

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

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


    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.

提交回复
热议问题