Monday, 24 December 2012

Read/Write files from SD Card – PhoneGap/HTML/Javascript

Javascript functions to list out the files in SD card and show it in html div tag
 
Read files
 function BrowseFile()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
var directoryReader = fs.root.createReader();
directoryReader.readEntries(function(entries) {
var i;
document.getElementById('dirList').innerhtml='';
var child="";
for (i=0; i<entries.length; i++) {
child=child+"<div>"+entries[i].toURI()+"</div>";
alert(entries[i].toURI());
}
document.getElementById('dirList').innerHTML = child;
}, function (error) {
alert(error.code);
})
}, function (error) {
alert(error.code);
});
} 
 
Create a file and write to it
function writeFile()
{
// root file system entry
var root = getFileSystemRoot();
// writes a file
write_file = function(writer)
{
var lineCount = 1;
// set the callbacks
writer.onwritestart = onFileEvent;
writer.onprogress = onFileEvent;
writer.onwrite = onFileWrite;
writer.onabort = onFileEvent;
writer.onerror = onFileError;
writer.onwriteend = function(event)
{
onFileEvent(event);
lineCount += 1;
if (lineCount <= 3)
{
// append a new line
writer.write('Line ' + lineCount + '.\r\n');
}
else {
alert(writer.fileName + ' length=' + writer.length + ', position=' + writer.position);
}
}
// append
writer.seek(writer.length);
// write to file
writer.write('Line ' + lineCount + '.\r\n');
},
// creates a FileWriter object
create_writer = function(fileEntry)
{
fileEntry.createWriter(write_file, onFileSystemError);
};
// create a file and write to it
root.getFile('bbgap2.txt', {create: true}, create_writer, onFileSystemError);
}

Reference links -
http://geekyfry.com/tech-it/smartphones/phonegap/reading-writing-files-from-sd-card-phonegaphtml5javascript/

No comments:

Post a Comment