You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LettingTheUserDownloadAFile.asciidoc 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. ---
  2. title: Letting The User Download A File
  3. order: 6
  4. layout: page
  5. ---
  6. [[letting-the-user-download-a-file]]
  7. = Letting The User Download A File
  8. Providing a file for download to the user might be trickier that what it
  9. seems - the file should be downloaded instead of just opened by the
  10. browser, download blockers should be avoided, a unique URL should be
  11. generated and server-side memory should be released when the file is no
  12. longer available for download. All this is taken care of by the new
  13. `FileDownloader` extension that can make almost any component start a
  14. download when clicked.
  15. [source,java]
  16. ....
  17. public class LettingUserDownladFile extends UI {
  18. @Override
  19. protected void init(VaadinRequest request) {
  20. Button downloadButton = new Button("Download image");
  21. StreamResource myResource = createResource();
  22. FileDownloader fileDownloader = new FileDownloader(myResource);
  23. fileDownloader.extend(downloadButton);
  24. setContent(downloadButton);
  25. }
  26. private StreamResource createResource() {
  27. return new StreamResource(new StreamSource() {
  28. @Override
  29. public InputStream getStream() {
  30. String text = "My image";
  31. BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
  32. bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20);
  33. try {
  34. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  35. ImageIO.write(bi, "png", bos);
  36. return new ByteArrayInputStream(bos.toByteArray());
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. return null;
  40. }
  41. }
  42. }, "myImage.png");
  43. }
  44. }
  45. ....
  46. To use `FileDownloader`, you just create an instance of the extension
  47. and use it to extend the component or `MenuItem` that should start the download. You
  48. should also note that `FileDownloader` works best with resources that
  49. are served by Vaadin as it relies on sending some special HTTP headers
  50. along with the file to ensure the browser doesn't try to open the file
  51. even if it's is a file type that the browser knows how to deal with.
  52. [[lazily-determine-the-content-and-the-name-of-the-file-being-server]]
  53. ==== Lazily determine the content and the name of the file being server
  54. One can lazily determine the content of the file using a
  55. `StreamResource`. Yet the name of the file that is going to be
  56. downloaded has to be known at creation time of the `FileDownloader`. It
  57. seems that a way around this, is in fact missing from Vaadin 7 as of
  58. now.
  59. A possible solution is to subclass `FileDownloader` and set the name right
  60. before the download happens:
  61. [source,java]
  62. ....
  63. /**
  64. * This specializes {@link FileDownloader} in a way, such that both the file name and content can be determined
  65. * on-demand, i.e. when the user has clicked the component.
  66. */
  67. public class OnDemandFileDownloader extends FileDownloader {
  68. /**
  69. * Provide both the {@link StreamSource} and the filename in an on-demand way.
  70. */
  71. public interface OnDemandStreamResource extends StreamSource {
  72. String getFilename ();
  73. }
  74. private static final long serialVersionUID = 1L;
  75. private final OnDemandStreamResource onDemandStreamResource;
  76. public OnDemandFileDownloader (OnDemandStreamResource onDemandStreamResource) {
  77. super(new StreamResource(onDemandStreamResource, ""));
  78. this.onDemandStreamResource = checkNotNull(onDemandStreamResource,
  79. "The given on-demand stream resource may never be null!");
  80. }
  81. @Override
  82. public boolean handleConnectorRequest (VaadinRequest request, VaadinResponse response, String path)
  83. throws IOException {
  84. getResource().setFilename(onDemandStreamResource.getFilename());
  85. return super.handleConnectorRequest(request, response, path);
  86. }
  87. private StreamResource getResource() {
  88. StreamResource result = null;
  89. this.getSession().lock();
  90. try {
  91. result = (StreamResource) this.getResource("dl");
  92. } finally {
  93. this.getSession().unlock();
  94. }
  95. return result;
  96. }
  97. }
  98. ....
  99. [[lazily-determine-the-content-and-the-name-of-the-file-being-server]]
  100. ==== Cancelled downloads
  101. Since downloadable files may be quite big, and the download process may take time, the user might decide to
  102. cancel the download process. In this case `IOException` may be thrown by the web server. That
  103. does not mean something went wrong with the application, but the user pressed `Cancel` button during download. To prevent the exception to be logged, you can catch and ignore it as here:
  104. ```java
  105. public class IgnoreCancelDownloader extends FileDownloader {
  106. ...
  107. @Override
  108. public boolean handleConnectorRequest(final VaadinRequest request, final VaadinResponse response, final String path) {
  109. try {
  110. return super.handleConnectorRequest(request, response, path);
  111. } catch (final IOException ignored) {
  112. return true;
  113. }
  114. }
  115. }
  116. ```
  117. Note that the exception is a sublclass of `IOException`, but the particular class depends on the web container.