Here's a useful little code snippet if you're building a web application. It's a simple way of making the boundary between web-browser and platform a bit smaller. It allows you to create a file (text, html, whatever) in in your page which the user can drag onto their desktop (if their browser supports the dragstart event and dataTransfer methods).

document.getElementById('downloadElement').addEventListener("dragstart", function (e) {
  e.dataTransfer.setData("DownloadURL", "text/html:filename.html:data:image/png;base64," + btoa(fileContent));
});

A description of the code:

  • attach an event listener to the draggable element you specify (downloadElement)
  • when you start to drag it (dragstart),
  • it creates a dataTransfer object (with the type DownloadURL)
  • and sets the content of that to be whatever you pass it (fileContent)
  • It uses btoa() to encode the string data as a base64-encoded string.
  • When you combine this with the MIME-type (text/html),
  • you can create a file with the specified name (filename.html) when the user releases the drag in their local file system.
  • The fake MIME-type (image/png) is there as part of the object data to convince the browser this is a binary file (which it is, even though it's not an image).

Credit goes to Paul Kinlan for using this in Appmator which is where I first saw this done this way. He actually uses it alongside some extremely clever JS zip-file creation stuff, too, it's definitely worth digging through the source there.

You can find out more about the drag events on the MDN.