In the last article we have discussed the Flags and the LocalFileSystem in PhoneGap. To read a file, we require a FileReader object. TheFileReader object is a way to read a file from the device's FileSystem. A file can be read as text, or as a Base64-encoded data string.
This object has the following properties.
- readyState : This is one of the three states (EMPTY, LOADING OR DONE), the reader can be in.
- result : This is used to get the content of the file that has been read.
- error : This is used for an object containing errors.
- onloadstart : This is called when we start reading.
- onload : This is called when the reading has successfully completed.
- onabort : This is called when the read has been aborted.
- onerror : This is called when the read has got failed.
- onloaded : This is called when the request has completed (either in success or failure).
This object has the following methods:
- abort.
- readAsDataUrl.
- readAsText.
abort
By using the abort() method, we can stop reading a file from the FileSystem as shown in the following code:
function success(file) {
var reader_file = new FileReader();
reader_file.onloadend = function (event) {
alert("read success");
alert(event.target.result);
};
reader_file.readAsText(file);
reader_file.abort();
}
function fail(error) {
console.log(error.code);
}
entry.file(success, fail);
readAsDataUrl.
Using the readAsDataUrl() method, we can read a file and return the data as Base64-encoded data, which is ideal for images and other binary files as shown in the following code:
function success(file) {
var file_reader = new FileReader();
file_reader .onloadend = function(evt) {
alert("read success");
alert(evt.target.result);
};
file_reader .readAsDataURL(file);
}
function fail(evt) {
console.log(error.code);
}
entry.file(success, fail);
ReadAsText
By using the ReadAsText() method, we can also read a file and return text, which is most suitable for TXT file as shown in the following code:
function success(file) {
var file_reader = new FileReader();
file_reader .onloadend = function(evt) {
alert("read success");
alert(evt.target.result);
};
file_reader .readAsDataURL(file);
}
function fail(evt) {
console.log(error.code);
}
entry.file(success, fail);
FULL EXAMPLE

bismita mohantyPosted Jul 25, 2013, 1:04 AM
This code doesn't work for Windows Phone. I have a "Sample.txt" file under www/js folder. The fileReader is unable to read its content and gets into the fail method every time.
Nitin ShettyPosted Aug 10, 2012, 5:05 AM
this code is not working for me..
Arun kumarPosted Mar 16, 2012, 4:28 AM
can to tell the steps to execute the above code... i'm trying for so many days and i cant... please tell steps to execute using phonegap... with regards, Arun