Phonegap (3.3.0) FileReader readAsText() not working - android

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);
});
}
);

Related

Display image from internal storage in Vue + Cordova

I am trying to display an image from download folder.
imagePath: file:///storage/emulated/0/Download/sample.png
Set Image URL:
window.resolveLocalFileSystemURL(this.imagePath, function success(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
if (this.result) {
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
this.imgUrl = window.URL.createObjectURL(blob);
}
};
reader.readAsArrayBuffer(file);
});
}, function (err) {
this.info = 'An error was found: '+ err;
});
Display it on UI:
<img class="img-fluid" src="{{imgUrl}}" />
But code is not reaching inside onloadend callback.

Cordova file upload not working on android

using cordova media-capture and file-transfer plugin I try to make an app to record video and upload on server. After recording video I call the upload function and it showing the success message in success callback function. But no file uploaded in server. Here my code.
$(document).ready(function(){
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:1});
}
var captureSuccess = function(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
};
var captureError = function(error) {
alert('error');
console.log(error);
};
/********* File Upload **********/
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://myserver.com/test.php",
function(result) {
alert('success');
},
function(error) {
alert('error');
},
{ fileName: name, fileKey: "file" });
}
My php code is
<?php
if($_FILES['file']['size'] > 0) {
$path = $_SERVER['DOCUMENT_ROOT']."/audior/app/";
$tmpname1 = $_FILES['file']['tmp_name'];
$ptname1 = $_FILES['file']['name'];
move_uploaded_file($tmpname1, $path . $ptname1);
echo 'success';
}
?>
You have to create a FileUploadOptions object
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = name;
then use it on the upload function
ft.upload(path,
"http://myserver.com/test.php",
function(result) {
alert('success');
},
function(error) {
alert('error');
},
options);
You can also change the
function(result) {
alert('success');
}
to
function(result) {
alert(result);
}
Just to check if the server is telling you something.
If you are getting the success callback the problem should be on the PHP script.
I use this one that returns the url of the uploaded file
<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], "./" . $_FILES["file"]["name"]);
echo "http://" . $_SERVER['SERVER_NAME'] . "/" . $target_file;
?>

Read text file on Android with Phonegap

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);
}
}

Display PDF in Android/iOS App

I have downloaded a PDF file as Base64 String in my phone as described in this SO Thread but I am not getting how can I render it to actual PDF so that end user can see it? I have written following code to write on the file:
var tempResponse = null;
function downloadFileOK(response){
var invocationResult = response['invocationResult'];
tempResponse = invocationResult;
var size = parseInt(invocationResult["responseHeaders"]["Content-Length"]);
window.requestFileSystem(LocalFileSystem.PERSISTENT, size, onSuccessFileHandler, onErrorFileHandler);
}
//Success
function onSuccessFileHandler(fileSystem) {
alert("inside onSuccessFileHandler START");
fileSystem.root.getFile("test2.pdf", {create: true, exclusive: false}, fileWriter, fail);
alert("inside onSuccessHandler END");
}
// Failure
function onErrorFileHandler(error) {
alert("inside onErrorFileHandler");
}
function fileWriter(entry){
alert("inside fileWriter START");
entry.createWriter(function(writer){
writer.onwriteend = function(evt) {
console.log("done written pdf :: test1.pdf");
alert("Inside onwriteend : START");
};
var temp = atob(tempResponse["text"]);
alert(temp);
writer.write(temp);
},fail);
alert("inside fileWriter END");
}
function fail(error) {
alert("inside fail");
console.log(error.code);
}
Am I doing it wrong? How can I open the PDF from my app in iOS/Android OS using javascript/jquery/cordova ?
Once you have download the base64 encoded file, you should decode it and save it to the file system so that it can be viewed later. You should not save the base in it's base64 encoded form.
You can use the utility function below to accomplish that. BTW you should take a look a the previous answer on Download PDF file from through MobileFirst Adapter since I made an update to it, it wasn't encoding the PDF properly.
var AppUtils = (function(){
// get the application directory. in this case only checking for Android and iOS
function localFilePath(filename) {
if(device.platform.toLowerCase() === 'android') {
return cordova.file.externalDataDirectory + filename;
} else if(device.platform.toLowerCase() == 'ios') {
return cordova.file.dataDirectory + filename;
}
}
// FileWritter class
function FileWritter(filename) {
this.fileName = filename;
this.filePath = localFilePath(filename);
}
// decode base64 encoded data and save it to file
FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
var byteData = atob(data);
var byteArray = new Array(byteData.length);
for (var i = 0; i < byteData.length; i++) {
byteArray[i] = byteData.charCodeAt(i);
}
var binaryData = (new Uint8Array(byteArray)).buffer;
this.saveFile(binaryData, ok, fail);
}
// save file to storage using cordova
FileWritter.prototype.saveFile = function(data, ok, fail) {
this.fileData = data;
var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));
var that = this;
// Write file on local system
window.resolveLocalFileSystemURL(path, function(directoryEntry) {
var options = {create: true, exclusive: false};
directoryEntry.getFile(that.fileName, options, function(file) {
file.createWriter(function(writer) {
writer.onwriteend = function(event) {
if(typeof ok === 'function') {
ok(event);
}
};
writer.write(that.fileData);
}, fail);
}, fail);
}, fail);
};
// open InApp Browser to view file
function viewFile(filename) {
var path = localFilePath(filename);
window.open(path, "_blank", "location=yes,hidden=no,closebuttoncaption=Close");
}
return {
FileWritter: FileWritter,
localFilePath: localFilePath,
viewFile: viewFile
}
})();
Your downloadFileOK should look as follow:
function downloadFileOK(response){
var pdfData = response['invocationResult']['text'];
var fileWritter = new AppUtils.FileWritter('YOUR-PDF-NAME.pdf');
fileWritter.saveBase64ToBinary(pdfData, function(r){
// file was saved
}, function(e){
// error file was not saved
});
}
If you want to open the file then you can use AppUtils.viewFile('YOUR-FILE-NAME.pdf')

Mp3 file to Base64 encode string conversion in android phonegap

I have a function to encode an mp3 file to base64 string.But when the file get executed some errors are generating.My function is follows :
function recordAudioToBase64() {
console.log('encodeing fun reached');
var file = 'jivebirdrecord.mp3';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFile, fail);
}
function gotFile(fileSystem) {
fileSystem.root.getFile("jivebirdrecord.mp3", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file) {
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
base = evt.target.result;
};
reader.readAsBinaryString(file);
}
function fail() {
console.log('failed......');
}
And i have the following error :
**processMessage failed: Error: TypeError: Failed to execute 'readAsDataURL' on 'FileReader': The argument is not a Blob.
processMessage failed: Stack: TypeError: Failed to execute 'readAsDataURL' on 'FileReader': The argument is not a Blob.
at FileReader.readAsDataURL (file:///android_asset/www/plugins/org.apache.cordova.file/www/FileReader.js:201:33)
at readDataUrl (file:///android_asset/www/js/script.js:293:14)
at gotFile (file:///android_asset/www/js/script.js:283:4)
at file:///android_asset/www/plugins/org.apache.cordova.file/www/requestFileSystem.js:52:25
at success (file:///android_asset/www/plugins/org.apache.cordova.file/www/fileSystems-roots.js:40:13)
at Object.cordova.callbackFromNative (file:///android_asset/www/cordova.js:292:54)
at processMessage (file:///android_asset/www/cordova.js:1039:21)
at Function.androidExec.processMessages (file:///android_asset/www/cordova.js:1076:13)
at pollOnce (file:///android_asset/www/cordova.js:944:17)
at pollOnceFromOnlineEvent (file:///android_asset/www/cordova.js:939:5)
processMessage failed: Message: S01 File810616738
[{"fullPath":"\/","filesystemName":"temporary","isDirectory":true,"nativeURL":"file:\/\/\/storage\/emulated\/0\/Android\/data\/com.phonegap.helloworld\/cache\/","filesystem":0,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"persistent","isDirectory":true,"nativeURL":"file:///storage/emulated/0/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"content","isDirectory":true,"nativeURL":"cdvfile://localhost/content/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"files","isDirectory":true,"nativeURL":"file:///data/data/com.phonegap.helloworld/files/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"files-external","isDirectory":true,"nativeURL":"file:///storage/emulated/0/Android/data/com.phonegap.helloworld/files/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"documents","isDirectory":true,"nativeURL":"file:///data/data/com.phonegap.helloworld/files/Documents/","filesystem":1,"isFile":false,"name":""},{"fullPath":"/","filesystemName":"sdcard","isDirectory":true,"nativeURL":"file:///storage/emulated/0/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"cache","isDirectory":true,"nativeURL":"file:///data/data/com.phonegap.helloworld/cache/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"cache-external","isDirectory":true,"nativeURL":"file:///storage/emulated/0/Android/data/com.phonegap.helloworld/cache/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"root","isDirectory":true,"nativeURL":"file:///","filesystem":1,"isFile":false,"name":""}]**
Please help me to find a solution for converting an mp3 file to base64 string using phonegap and jquery mobile.
Thnaks
It's bit late but for others this might help.
directoryReader.readEntries(function(entries){
for (var i=0; i<entries.length; i++) {
var reader = new FileReader();
var entry = entries[i];
entry.file(function(file){
reader.readAsDataURL(file);
reader.onload = doOnload(entry.name);
});
}
});

Categories

Resources