Read text file on Android with Phonegap - android

I am simply trying to read a text file on my Android with Phonegap. I have looked at all of the examples and I don't see a difference in my code. The file has lines of text. onloadend results in length of 0. There are no errors. What am I missing here?
function readTextFile(fileName) {
window.requestFileSystem(LocalFileSystem.TEMPORARY, 5*1024*1024,
successCallback, errorCallback);
function successCallback(fs) {
fs.root.getFile(fileName, {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log("TEXT FILE LENGTH: " + this.result.length);
};
reader.readAsText(file);
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
console.log("ERROR: " + error.code);
}
}

Related

Cordova read external archive and play

I am creating an app with cordova for android using plugin file-transfer. The download is going to a certain folder but I can't read the file despite indicating the correct path follows the code
var uri = encodeURI(mypage);
var fileURL = cordova.file.externalDataDirectory + "teste.ogg";
fileTransfer.download(
uri, fileURL, function(entry) {
console.log("download complete: " + entry.toURL());
$("#audio-teste").attr('src',fileURL)
/*--codigo de teste--*/
var meuFile = cordova.file.externalDataDirectory;
resolveLocalFileSystemURL(meuFile, function(entry) {
var readerN = fileSystem.createReader();
readerN.readEntries(
function (entry) {
var arrayN =[];
for(var i="0"; i < entry.length; ++i){
var entradaN = entry[i].name;
arrayN.push(entradaN);
//console.log(array);
console.log('teste aq' + arrayN);
}
}
)
//console.log(entry);
});
/*----*/
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
/*----*/
The cordova plugin cordova-plugin-file-transfer is due to be deprecated and its latest npm version fails on iOS.
Therefore these two working functions are purely based on vanilla JS, and thus no need to use extra plugins, besides the standard plugin cordova-plugin-file. Therefore this is compatible with any platform.
https://gist.github.com/jfoclpf/07e52f6bdf9c967449c4bc06af44c94a
I paste here for your convenience:
// for different types of cordovaFileSystem check here:
// https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/#where-to-store-files
// or simply type in the console `console.log(cordova.file)`
function downloadFileToDevice (fileurl, filename, cordovaFileSystem, callback) {
var onerror = (err) => {
console.error(`Error downloading from ${fileurl} to cordovaFileSystem ${cordovaFileSystem}`,
err, new Error(err))
if (typeof callback === 'function') { callback(Error(err)) }
}
var blob = null
var xhr = new XMLHttpRequest()
xhr.open('GET', fileurl)
xhr.responseType = 'blob' // force the HTTP response, response-type header to be blob
xhr.onload = () => {
blob = xhr.response // xhr.response is now a blob object
var DataBlob = blob
window.resolveLocalFileSystemURL(cordovaFileSystem, (dirEntry) => {
const sanitizedFilename = filename.replace(/[^a-z0-9\.]/gi, '_').toLowerCase() // sanitize filename
dirEntry.getFile(sanitizedFilename, { create: true }, (file) => {
file.createWriter((fileWriter) => {
fileWriter.write(DataBlob)
if (typeof callback === 'function') { callback(null, cordovaFileSystem + sanitizedFilename) }
}, (err) => { console.error('Error on file.createWriter'); onerror(err) })
}, (err) => { console.error('Error on dirEntry.getFile'); onerror(err) })
}, (err) => { console.error('Error on resolveLocalFileSystemURL'); onerror(err) })
}
xhr.onerror = (err) => { console.error('Error on XMLHttpRequest'); onerror(err) }
xhr.send()
}
An example for downloading a file
downloadFileToDevice('https://example.com/img.jpg',
'myImg.jpg',
cordova.file.cacheDirectory,
(err, localFilePath) => {
if (err) {
console.error('An error occured downloading file:', err)
} else {
console.log('Download file with success: ' + localFilePath)
}
})
Can you try with this? I tried and it works like a charm

read uploaded vcf file from server

I have uploaded vcf file successfully on server on getting help from my previous question (the one which is edited)
Now I need a help in how to read that vcf file or vcard from server and display as a contact number and contact name in my phonegap app.
plugin used cordova-plugin-file-transfer
Can anyone help on this ?
Using plugin cordova-plugin-file-transfer https://github.com/apache/cordova-plugin-file-transfer you can download file from server.
For Read vcf file, you need https://github.com/nilclass/vcardjs JavaScript based library. you can directly use .js files.
You can follow below example.
window.requestFileSystem(window.TEMPORARY, 1 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
var fileName = "temp.vcf";
var dirEntry = fs.root;
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
download(fileEntry,"server-path-to-file.vcf");
}, onErrorCreateFile);
}, onErrorLoadFs);
function download(fileEntry, uri) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("Successful download...");
console.log("download complete: " + entry.toURL());
readFile(entry);
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
function readFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log("Successful file read: " + reader.result);
reader.parseVCard(reader.result);
};
reader.readAsText(file);
}, onErrorReadFile);
}
function parseVCard(vCarddata){
VCF.parse(vCarddata, function(vcard) {
// this function is called with a VCard instance.
// If the input contains more than one vCard, it is called multiple times.
console.log("Formatted name", vcard.fn);
console.log("Names", JSON.stringify(vcard.n));
});
//Fore more help:https://github.com/nilclass/vcardjs
}

How to implement a piece of code within a hyperlink?

I have often seen peices of codes such as this one:
window.resolveLocalFileSystemURI(FILE_URL, function(e){
e.file(function(f){
var reader = new FileReader();
reader.onloadend = function(evt) {
PDFJS.getDocument(new Uint8Array(evt.target.result)).then(function(pdf) {
//do whatever you want with the pdf, for example render it using 'pdf.getPage(page) and page.render() functions
}, function (error) {
console.log("PDFjs error:" + error.message);
});
};
reader.readAsArrayBuffer(f);
});
}, function(e){
console.log("error getting file");
});
and I am not sure how to implment it wihtin my html.
Would it be like this:
<a href=" ../res/DOC140416-1.pdf" onclick=window.resolveLocalFileSystemURI(FILE_URL, function(e){
e.file(function(f){
var reader = new FileReader();
reader.onloadend = function(evt) {
PDFJS.getDocument(new Uint8Array(evt.target.result)).then(function(pdf) {
'pdf.getPage(page)
}, function (error) {
console.log("PDFjs error:" + error.message);
});
};
reader.readAsArrayBuffer(f);
});
}, function(e){
console.log("error getting file");
}); >
link to my pdf 2</a>
If not hos should it be done?
This piece of code was got from a SO question
Thanks!

How to download music that stored in http server in Angularjs

Let's say I have a API that stores some .mp3 music.
The sample link here:
https://118.69.201.34:8882/api/ApiMusic/Download?songId=2000
Now I want to write an API calling function in Angularjs to download the music to my Android devices with the song's Id number as in the link.
How can I do that? Please help :(
You can use the ngCordova FileTransfer library here: http://ngcordova.com/docs/plugins/fileTransfer/
Here's example code from that page, tweaked to your example URL:
document.addEventListener('deviceready', function () {
var fileid = "2000";
var url = "https://118.69.201.34:8882/api/ApiMusic/Download?songId=" + fileid;
var targetPath = cordova.file.documentsDirectory + fileid + ".mp3";
var trustHosts = true
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
}, function(err) {
// Error
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}, false);
I did it finally, here is my code. Just share for those who want to refer to this issue in the future. Thanks you guys for your answers
$scope.download = function(songId, songName) {
$ionicLoading.show({
template: 'Downloading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getDirectory(
"fMusic",
{
create: true
},
function (dirEntry) {
dirEntry.getFile(
songName + ".mp3",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI(APIUrl + songId),
p,
function (entry) {
$ionicLoading.hide();
$scope.mp3File = entry.toURL();
},
function (error) {
$ionicLoading.hide();
alert("Download Error Source --> " + error.source);
},
false,
null
);
},
function () {
$ionicLoading.hide();
console.log("Get the file failed");
}
);
}
);
},
function () {
$ionicLoading.hide();
console.log("Request for filesystem failed");
});
}

Phonegap (3.3.0) FileReader readAsText() not working

so I am trying to use the phonegap file API to save and later load a file in the app. The save seems to be working, but reading the file throws this error:
processMessage failed: Stack: TypeError: Object #<an Object> has no method 'readAsText'
at [object Object].readAsText (file:///android_asset/www/plugins/org.apache.cordova.file/www/FileReader.js:130:33)
at file:///android_asset/www/index.html:3843:15
at file:///android_asset/www/plugins/org.apache.cordova.file/www/DirectoryEntry.js:100:9
at Object.callbackFromNative (file:///android_asset/www/phonegap.js:292:54)
at processMessage (file:///android_asset/www/phonegap.js:1029:21)
at Function.processMessages (file:///android_asset/www/phonegap.js:1063:13)
at pollOnce (file:///android_asset/www/phonegap.js:933:17)
at pollOnceFromOnlineEvent (file:///android_asset/www/phonegap.js:928:5)
No matter what I do, it always seems to throw this error. I printed out the fileReader object to the console and inspected it using weinre. It had the prototype with the readAsText() function on it, so I'm really at a loss why it's not working...
This is how I am saving the file:
var request = window.requestFileSystem;
if(typeof request != 'undefined') {
var fileSystem;
var writer;
request(LocalFileSystem.PERSISTENT, 0, function (FS) {
fileSystem = FS;
fileSystem.root.getFile("offlineData.txt", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(w) {
writer = w;
writer.write('This is some text yo');
}, function(e) {console.log(e);});},
function(e) {console.log(e); console.log('There was an error getting the file to write')});} ,
function(e) {\console.log('There was an error getting the file system');});}
Later in the flow, I will do something like this:
request(LocalFileSystem.PERSISTENT, 0, function(FS) {
fileSystem = FS;
fileSystem.root.getFile("offlineData.txt", null, function(_file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
console.log("read success");
console.log(evt.target.result);
};
reader.onerror = function(evt) {
console.log("Error read text");
console.log("Error"+evt.error.code);
};
reader.onabort = function(evt) {
console.log("aborted read text");
console.log(evt.target.result);
};
reader.onloadstart = function(evt) {
console.log("started reading");
};
console.log(reader);
reader.readAsText(_file);
});
}, function(e) {console.log(e); console.log('There was an error getting the file.')});
In your sample, _file is a fileEntry and not file content. Can you try this :
fileSystem.root.getFile("offlineData.txt", null,
function (fileEntry) {
fileEntry.file(function (_file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log("read success");
console.log(evt.target.result);
};
reader.readAsText(_file);
});
}
);

Categories

Resources