Letting The User Download A File

Providing a file for download to the user might be trickier that what it seems - the file should be downloaded instead of just opened by the browser, download blockers should be avoided, a unique URL should be generated and server-side memory should be released when the file is no longer available for download. All this is taken care of by the new FileDownloader extension that can make almost any component start a download when clicked.

Java

  1. public class LettingUserDownladFile extends UI {
  2. @Override
  3. protected void init(VaadinRequest request) {
  4. Button downloadButton = new Button("Download image");
  5. StreamResource myResource = createResource();
  6. FileDownloader fileDownloader = new FileDownloader(myResource);
  7. fileDownloader.extend(downloadButton);
  8. setContent(downloadButton);
  9. }
  10. private StreamResource createResource() {
  11. return new StreamResource(new StreamSource() {
  12. @Override
  13. public InputStream getStream() {
  14. String text = "My image";
  15. BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
  16. bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20);
  17. try {
  18. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  19. ImageIO.write(bi, "png", bos);
  20. return new ByteArrayInputStream(bos.toByteArray());
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. return null;
  24. }
  25. }
  26. }, "myImage.png");
  27. }
  28. }

To use FileDownloader, you just create an instance of the extension and use it to extend the component or MenuItem that should start the download. You should also note that FileDownloader works best with resources that are served by Vaadin as it relies on sending some special HTTP headers along with the file to ensure the browser doesn’t try to open the file even if it’s is a file type that the browser knows how to deal with.

Lazily determine the content and the name of the file being server

One can lazily determine the content of the file using a StreamResource. Yet the name of the file that is going to be downloaded has to be known at creation time of the FileDownloader. It seems that a way around this, is in fact missing from Vaadin 7 as of now.

A possible solution is to subclass FileDownloader and set the name right before the download happens:

Java

  1. /**
  2. * This specializes {@link FileDownloader} in a way, such that both the file name and content can be determined
  3. * on-demand, i.e. when the user has clicked the component.
  4. */
  5. public class OnDemandFileDownloader extends FileDownloader {
  6. /**
  7. * Provide both the {@link StreamSource} and the filename in an on-demand way.
  8. */
  9. public interface OnDemandStreamResource extends StreamSource {
  10. String getFilename ();
  11. }
  12. private static final long serialVersionUID = 1L;
  13. private final OnDemandStreamResource onDemandStreamResource;
  14. public OnDemandFileDownloader (OnDemandStreamResource onDemandStreamResource) {
  15. super(new StreamResource(onDemandStreamResource, ""));
  16. this.onDemandStreamResource = checkNotNull(onDemandStreamResource,
  17. "The given on-demand stream resource may never be null!");
  18. }
  19. @Override
  20. public boolean handleConnectorRequest (VaadinRequest request, VaadinResponse response, String path)
  21. throws IOException {
  22. getResource().setFilename(onDemandStreamResource.getFilename());
  23. return super.handleConnectorRequest(request, response, path);
  24. }
  25. private StreamResource getResource() {
  26. StreamResource result = null;
  27. this.getSession().lock();
  28. try {
  29. result = (StreamResource) this.getResource("dl");
  30. } finally {
  31. this.getSession().unlock();
  32. }
  33. return result;
  34. }
  35. }

Cancelled downloads

Since downloadable files may be quite big, and the download process may take time, the user might decide to cancel the download process. In this case IOException may be thrown by the web server. That 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:

Java

  1. public class IgnoreCancelDownloader extends FileDownloader {
  2. ...
  3. @Override
  4. public boolean handleConnectorRequest(final VaadinRequest request, final VaadinResponse response, final String path) {
  5. try {
  6. return super.handleConnectorRequest(request, response, path);
  7. } catch (final IOException ignored) {
  8. return true;
  9. }
  10. }
  11. }

Note that the exception is a sublclass of IOException, but the particular class depends on the web container.