Webアプリケーションなどでファイルをダウンロードさせたいと思ったことはないでしょうか。別なタブで開いて自分で保存してくださいというのは格好悪いです。ZipなどであればWebブラウザ任せですが、画像などはそうはいきません。 そこで使いたいのがdownloadです。とても簡単で使いやすいダウンロードライブラリです。

downloadの使い方

テキストの場合です。文字列、data、Blob、ファイル指定と様々な方法が用意されています。

download("hello world", "dlText.txt", "text/plain");
download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");
download(new Blob(["hello world"]), "dlTextBlob.txt", "text/plain");
download("/robots.txt");

var str= "hello world",	arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
  arr[b]=a.charCodeAt();
});

download( arr, "textUInt8Array.txt", "text/plain" );

HTMLのダウンロード。こちらも様々な方法が用意されています。

download(document.documentElement.outerHTML, "dlHTML.html", "text/html");
download(new Blob(["hello world".bold()]), "dlHtmlBlob.html", "text/html");
$.ajax({
	url: "/download.html",
	success: download.bind(true, "text/html", "dlAjaxCallback.html")
});

画像も使えます。Blobであれば、Canvasで生成してダウンロード実行というのもよさそうです。

download("/diff6.png");

var x=new XMLHttpRequest();
x.open( "GET", "/diff6.png" , true);
x.responseType="blob";
x.onload= function(e){download(e.target.response, "awesomesauce.png", "image/png");};
x.send();

downloadのいいところはやはり使い方がとても簡単ということでしょう。ファイルデータとファイル名、MimeTypeを指定するだけで完了します。ファイル名も自由に指定できるので、広い場面で使えそうです。

downloadはJavaScript製のオープンソース・ソフトウェア(MIT License)です。

rndme/download: file downloading using client-side javascript