Friday, 5 April 2013

Prompting the user to download a Data URI and specifying the name it should take

The following Javascript code allows you to prompt the user to download a Data URI and suggest it's name. It works in Chrome, check for other browsers you wish to support.

function downloadWithName(uri, name) {

 function eventFire(el, etype){
  if (el.fireEvent) {
   (el.fireEvent('on' + etype));
  } else {
   var evObj = document.createEvent('Events');
   evObj.initEvent(etype, true, false);

 var link = document.createElement("a"); = name;
 link.href = uri;
 eventFire(link, "click");

For example, calling
downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")
will prompt the user to download a text file called helloWorld.txt containing "Hello World".

No comments:

Post a Comment