Monday, 30 September 2013

Download Client Side Data As A File Using The Dart Language

A quick Dart tip! I am working on an update to the Dart Class Generator and wanted to improve the User experience from COPY + PASTE. In HTML5, it is possible to send data from a variable to the client as a file download from client side code. Best of all it is really easy to code - this example is for text.To use put a call to this in your button handling code.

  void downloadFileToClient(String filename, String text){
    AnchorElement tl = document.createElement('a');
    tl..attributes['href'] = 'data:text/plain;charset=utf-8,' + Uri.encodeComponent(text)
      ..attributes['download'] = filename
      ..click();   
  }

That's it - nothing server side required at all! I should emphasise this is also possible in pure JS - can't comment on browser support.