I want to assign String
content to a variable and enable the user to download that String as a text file.
I know there is FileDownloader
from Vaadin 8 which I can use but I don't want static file/image download capability but rather dynamic String content which can downloaded a text file in the browser.
The resource interface in Vaadin, that is used by FileDownloader
is a bit cumbersome. Especially so for dynamically created content, whose generation you'll want to postpone until user actually clicks the download button, which is very common in typical Vaadin apps.
Thus, I suggest to add Viritin add-on to your application. Use the DownloadButton
component from it, which simplifies the usage a lot.
Here is a trivial example:
DownloadButton simple = new DownloadButton(out -> {
try {
out.write("Foobar".getBytes());
} catch (IOException ex) {
// exception handling
}
}).withCaption("Simple Download");
To see more complete example, refer to the tests in the Viritin project. From the project you can also see the "raw solution" if you peruse the source code of DownloadButton
class.
PS. I'm the author of Viritin, so kind of biased to suggest its usage, but I have also been working with Vaadin for Vaadin Ltd for over a decade.