PhoneGapでローカルにバイナリファイルを読み書き
【index.html】
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>A</title> <script type="text/javascript" charset="utf-8" src="phonegap-1.4.0.js"></script> <script type="text/javascript" charset="utf-8" src="downloader.js"></script> <script type="text/javascript" charset="utf-8"> //var url = "http://wisteriahill.sakura.ne.jp/jqm_staticmap/logo_gamba.jpg"; var read_filename = ""; // +++ download +++++ function dl_file(){ var url = document.getElementById("data_url").value; window.plugins.downloader.downloadFile(url, {overwrite: true}, function(res) { var progress = parseJSON(JSON.stringify(res)); document.getElementById("status").value = progress; }, function(error) { alert("err" + error); } ); } function parseJSON(jsData){ var data = eval("("+jsData+")"); var resultData = ""; resultData += data.progress + "%,"; resultData += data.total + ","; resultData += data.status + ","; read_filename = data.file; resultData += data.file; return resultData; } // +++ read data +++++ function readFile(){ window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS_R, fail); } function gotFS_R(fileSystem) { var filename = "download/" + read_filename; fileSystem.root.getFile(filename, {create: true}, gotFileEntry_R, fail); } function gotFileEntry_R(fileEntry) { fileEntry.file(gotFile, fail); } function gotFile(file){ readAsDataURL(file); } function readAsDataURL(file) { var reader = new FileReader(); reader.onloadend = function(evt) { var saved_data = evt.target.result; document.getElementById("saved_data").src = saved_data; }; reader.readAsDataURL(file); } //error function fail(error) { alert(error.code); } </script> </head> <body> ファイル <BR> <img src="http://wisteriahill.sakura.ne.jp/jqm_staticmap/logo_gamba.jpg"> <textarea rows=3 cols=30 id="data_url" value="">http://wisteriahill.sakura.ne.jp/jqm_staticmap/logo_gamba.jpg</textarea> <BR> <input type="button" value="ダウンロード" onClick="dl_file()"> <BR> ステータス<input type="test" id="status" size=25 value=""> <BR> <input type="button" value="再読み込み" onClick="readFile()"> <BR> <img src="" id="saved_data"> <BR> </body> </html>