2

I want to do what Downloadify does in this other question: How do I dynamically create a document for download in Javascript?

But I would like to do it without using Flash. How can that be done?

Community
  • 1
  • 1
quantumpotato
  • 9,637
  • 14
  • 70
  • 146

1 Answers1

3

I think the best you can do is something like this:

function addDownloadLinkTo(elem, base64data) {
    var link = document.createElement('a');
    var text = document.createTextNode('Download');
    link.appendChild(text);
    link.setAttribute('href', 'data:application/octet-stream;base64,' + base64data);
    elem.appendChild(link);
}

Or if you're using jQuery,

$(elem).append($('<a href="data:application/octet-stream;base64,' + base64data + '">Download</a>');

where base64data can be obtained as in this question.

Unfortunately, data URIs do not yet (AFAIK) provide a mechanism to specify the file name; also, might not work in all browsers.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Thanks - that gets me text files easily. I tried doing cat file.mp3 | pbcopy, pasting that into my base64data generation, but I get an error on the page "unterminated string" probably because the paste contains both ' and " characters. – quantumpotato Dec 25 '11 at 05:56
  • I saved foo.mp3 from a text editor and opened in vlc. I got the title of the song, but the file wouldn't play. 0:00 duration – quantumpotato Dec 25 '11 at 05:59
  • oh, i thought you were doing it *in* JS. Try `openssl base64 -d -in file.mp3 -out file.base64` – Amadan Dec 25 '11 at 06:14
  • I will, I just don't have the song data on the website yet. So I tried pasting from the command line. WHen I run your command I get file.base64 with 0 size openssl base64 -d -in SilkRain.mp3 -out file.base64 – quantumpotato Dec 25 '11 at 23:47
  • Whoops, without the `-d`. That's the other direction. (blush) – Amadan Dec 26 '11 at 03:11