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);
   el.dispatchEvent(evObj);
  }
 }

 var link = document.createElement("a");
 link.download = 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".

2 comments:

  1. it's not working on chrome, it's not taking the file name I want to use

    ReplyDelete