The FileReader API works great as long as the file you want to read is on the device's file system. However if you want to read a file you've packed in the Android assets folder you would need to use XHR to read the file. I'm providing an interface that follows the same API as the regular FileReader. Of course the XhrFileReader is not limited to only reading files from the assets folder, it can also read files from the file system and over HTTP.
Adding the plugin to your project
To install the plugin, move XhrFileReader.js to your project's www folder and include a reference to it in your html files.
Using the plugin
To instantiate a new reader use the folling code:
var reader = cordova.require("cordova/plugin/xhrfilereader");Setup your event handlers:
// called once the reader beginsUnfortunately, you will only get an error on files read over HTTP. When you specify a file:// path the request status is always 0. There is no way to tell between a successful read or an error. So if you specify a file that does not exist like "file:///does.not.exist.txt" you will get an empty evt.target.result in your onloadend handler.
reader.onloadstart = function() {
console.log("load start");
};
// called when the file has been completely read
reader.onloadend = function(evt) {
console.log("File read");
console.log(evt.target.result);
};
// called if the reader encounters an errorProgress events are fired but are not very useful as they don't contain partial results.
reader.onerror = function(error) {
console.log("Error: " + error.code);
};
// called while the file is being readFinally call your read method, for instance:
reader.onprogress = function(evt) {
console.log("progress");
};
reader.readAsText("http://www.google.com"); reader.readAsText("file:///android_asset/www/config.json"); reader.readAsText("file:///sdcard/error.log");and that's about it. Obviously, this plugin is most useful when you need to read a text file from the assets folder.
Github: https://github.com/macdonst/XhrFileReader
No comments:
Post a Comment