Vaadin 7 - instant download of dynamically created

2019-08-01 09:15发布

问题:

My scenario is: using Vaadin 7.7.10, I have on click generated file, that I want to download once it is generated.

I have generator method, that returns byte[] (could be also easily modified to any OutputStream if needed), then I create StreamResource from it. So I have the resource ready to be downloaded, but now what?

I believe can't use approach with FileDownloader, because there I would have to generate the file every time the page is displayed prior to actual click on extended button (and I don't want to do that, as it is quite expensive operation which will shall only be used on demand).

I was able to achieve the desired effect using Page.getCurrent().open(streamResource, null, false), but .open with Resource argument is deprecated since Vaadin 7, so I don't wanna rely on it...

Is there any workaround or another approach to this?

回答1:

Vaadin FileDownloader might be still capable to handle this with some customization. However I once created a reporting system with a different approach. The idea is to use component BrowserFrame that takes StreamResource as its constructor param.

File generation is started - for example - by clicking a button. When generation finalizes it results in to a byte[]. From byte[] is created a StreamSource which then is used to create StreamResouce which is then used as contents of BrowserFrame.

Finally this BrowserFrame is added to the ui somewhere which causes browser to react.

In my case there was a need to generate parameterized PDF reports which user could first preview and then download if in need. I had a PDF generator that provided the byte[]. Browser recognized type from file name extension .pdf and opened PDF plugin for preview & download.

You can put any binary stuff to byte[] used to construct BrowserFrame and set appropriate file name extension.

You can also have some Layout in your ui that - for example - has a progress indicator while file is generating in the background and in to which the BrowserFrame component is attached when file is ready.