Cordova Audio Recorder API Plugin Unable find file - javascript

I am using the "Cordova Audio Recorder API Plugin" in my app its working great,but i am unable find the recorded file,In plugin they say it is stored in
"iOS: /var/mobile/Applications//Library/NoCloud/.m4a"
"Android: /data/data//files/.m4a"
I am unable to get it,even i try to change the directory but still no luck below is code which i change the directory.Need help
window.plugins.audioRecorderAPI.record(function(savedFilePath) {
var fileName = savedFilePath.split('/')[savedFilePath.split('/').length - 1];
var directory;
if (cordova.file.documentsDirectory) {
directory = cordova.file.documentsDirectory; // for iOS
} else {
directory = cordova.file.externalRootDirectory; // for Android
}
$cordovaFile.copyFile(
cordova.file.dataDirectory, fileName,
directory, "new_file.m4a"
)
.then(function (success) {
alert(JSON.stringify(success));
}, function (error) {
alert(JSON.stringify(error));
});
}, function(msg) {
alert('ko: ' + msg);
}, 3);

Related

how to create or write a file in android on phonegap?

I am using below code to write a file on android using PhoneGap, I think that this line window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { is giving the error, can't find the exact error, just because I can't debug on android.
I find PhoneGap documentation confusing.
function download_file(cur_filename)
{
alert(5);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
alert(2);
console.log('file system open: ' + fs.name);
alert(3);
fs.root.getFile(cur_filename, { create: true, exclusive: false }, function (fileEntry) {
alert("fileEntry is file?" + fileEntry.isFile.toString());
// fileEntry.name == 'someFile.txt'
fileEntry.name==cur_filename;
// fileEntry.fullPath == '/someFile.txt'
writeFile(fileEntry, null);
}, onErrorCreateFile);
}, onErrorLoadFs);
}
function writeFile(fileEntry, dataObj) {
aler(4);
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['some file data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
}
Firstly, you can directly download the file rather than having to create and write a new one. You need to first install the following plugins
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
Now, you need to enclose the below logic inside deviceready event in case you are accessing plugins on app launch. The file-transfer ships with a download() that you need to use for downloading your file. Please find a sample code below
document.addEventListener("deviceready", startDownload, false);
function startDownload() {
var fileTransfer = new FileTransfer();
// replace uri with -> http://192.168.43.54/text.csv
var uri = encodeURI("https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1920_18MG.mp4");
fileTransfer.download(
uri,
cordova.file.dataDirectory + 'videos/big_buck_bunny_720p_1mb.mp4',
function(entry) {
console.log("download complete: ", entry);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
}
);
}
Once the download is completed, the entry object will have a nativeURL property that holds the local URL to the file.
More info
File Plugin
File-Transfer Download

Ionic 3 - download a file to directory

I have the similar problem like here:
How to download file to Download's directory with Ionic Framework?
I got success alert after download but I can't see the file in an Android file explorer under the path displayed after succeed download: file:///data/user/0/io.ionic.fileTest/image.jpg
My code:
download(){
const fileTransfer: FileTransferObject = this.transfer.create();
const url = "http://cdna.allaboutvision.com/i/conditions-2016/heterochromia-kate-bosworth-660x660-with-credit.jpg";
fileTransfer.download(url, this.file.dataDirectory + 'laska.jpg', true).then((entry) => {
const alertSuccess = this.alertCtrl.create({
title: `Download Succeeded!`,
subTitle: `was successfully downloaded to: ${entry.toURL()}`,
buttons: ['Ok']
});
alertSuccess.present();
}, (error) => {
const alertFailure = this.alertCtrl.create({
title: `Download Failed!`,
subTitle: `was not successfully downloaded. Error code: ${error.code}`,
buttons: ['Ok']
});
alertFailure.present();
});
}
Could I somehow manage to save this file in e.g "Download" folder or "Documents"? I also tried changing destination path to:
cordova.file.externalRootDirectory + '/Download/'
In that case, I received error 1.
In many examples I see people use
window.requestFileSystem()
but it looks like the window doesn't have this method for me. I use visual studio code and ionic 3.
You got little bit mistake in fileTransfer.download
instead of this.file.applicationStorageDirectory use this.file.dataDirectory
Working code that downloads a file to Downloads directory:
downloadFile() {
this.fileTransfer.download("https://cdn.pixabay.com/photo/2017/01/06/23/21/soap-bubble-1959327_960_720.jpg", this.file.externalRootDirectory +
'/Download/' + "soap-bubble-1959327_960_720.jpg").then()
}
getPermission() {
this.androidPermissions.hasPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
.then(status => {
if (status.hasPermission) {
this.downloadFile();
}
else {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
.then(status => {
if(status.hasPermission) {
this.downloadFile();
}
});
}
});
}

FileOpener2 causing Attempt to invoke virtual method in cordova.js file on Android 6.0 or higher

We use FileOpener2 plugin for cordova to open a downloaded .apk file from our servers. Recently, we found that Android 6.0 or higher devices are throwing an exception only on the file open process. We were able to trace this down to the cordova.js file, where the posted exception occurs. We have yet to find a cause or a fix, but have put a workaround in place. Any info would be amazing on this so we can maintain our in-app self updating process going on all Android devices.
Code (Working on Android <= 6.0):
// we need to access LocalFileSystem
window.requestFileSystem(LocalFileSystem.PERSISTENT, 5 * 1024 * 1024, function (fs) {
//Show user that download is occurring
$("#toast").dxToast({
message: "Downloading please wait..",
type: "warning",
visible: true,
displayTime: 20000
});
// we will save file in .. Download/OURAPPNAME.apk
var filePath = cordova.file.externalRootDirectory + '/Download/' + "OURAPPNAME.apk";
var fileTransfer = new FileTransfer();
var uri = encodeURI(appDownloadURL);
fileTransfer.download(uri, filePath, function (entry) {
//Show user that download is occurring/show user install is about to happen
$("#toast").dxToast({
message: "Download complete! Launching...",
type: "success",
visible: true,
displayTime: 2000
});
////Use pwlin's fileOpener2 plugin to let the system open the .apk
cordova.plugins.fileOpener2.open(
entry.toURL(),
'application/vnd.android.package-archive',
{
error: function (e) {
window.open(appDownloadURL, "_system");
},
success: function () { console.log('file opened successfully'); }
}
);
},
function (error) {
//Show user that download had an error
$("#toast").dxToast({
message: error.message,
type: "error",
displayTime: 5000
});
},
false);
})
Debugging Information:
THIS IS NOT OUR CODE, BUT APACHE/CORDOVA CODE
Problem File: cordova.js
function androidExec(success, fail, service, action, args) {
// argsJson - "["file:///storage/emulated/0/download/OURAPPNAME.apk","application/vnd.android.package-archive"]"
//callbackId - FileOpener21362683899
//action - open
//service FileOpener2
//bridgesecret - 1334209170
// msgs = "230 F09 FileOpener21362683899 sAttempt to invoke virtual method 'android.content.res.XmlResourceParser //android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference"
var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);
// If argsJson was received by Java as null, try again with the PROMPT bridge mode.
// This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.
if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "#Null arguments.") {
androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);
androidExec(success, fail, service, action, args);
androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);
} else if (msgs) {
messagesFromNative.push(msgs);
// Always process async to avoid exceptions messing up stack.
nextTick(processMessages);
}

How do you upload a video to a node js server in nativescript?

In my nativescript app, I'm able to record a video, but I want to upload it to an S3 bucket for later streaming. I'm running a node js server that handles the api for my app.
I'm trying to use the 'nativescript-background-http' library, but it always breaks when I try to run the uploadFile function.
Here's the relevant code:
var uploadVideo = function (filepath) {
console.log("Attempting to upload video...");
var session = bghttp.session("video-upload");
var filename = filepath.replace(/^.*[\\\/]/, '');
var request = {
url: config.apiUrl + 'upload',
method: "POST",
headers: {
"Content-Type": "video/mp4",
"File-Name": filename
},
description: "{ 'uploading': filename }"
};
try {
var task = session.uploadFile(filepath, request);
task.on("progress", logEvent);
task.on("error", logEvent);
task.on("complete", logEvent);
function logEvent(e) {
console.log("Logging event.");
console.dir(e);
console.log(e.eventName);
}
}
catch (error) {
console.dir(error);
console.log("An error occurred uploading the file. Removing video from filesystem...");
var documents = fs.knownFolders.documents();
var file = documents.getFile(filename);
file.remove()
.then(function (result) {
console.log("The video has been removed successfully.");
}, function (error) {
console.log("The video could not be removed from the file system.");
console.dir(error);
});
}
};
This is the output I end up with:
JS: Video located at /data/user/0/org.nativescript.Lifey/files/videoCapture_1486072596043.mp4
JS: Attempting to upload video...
JS: === dump(): dumping members ===
JS: {
JS: "nativeException": {
JS: "constructor": "constructor()function () { [native code] }"
JS: }
JS: }
JS: === dump(): dumping function and properties names ===
JS: === dump(): finished ===
JS: An error occurred uploading the file. Removing video from filesystem...
JS: The video has been removed successfully.
Any idea what's going on? Does 'nativescript-background-http' library even support video uploads (I've only seen image upload examples on their github)? Is there some alternative that I could use if I can't use that library?

Chrome Apps : How to save blob content to fileSystem in the background?

In Chrome Apps, I'm downloading a blob content from a server using JavaScript XHR (Angular $http GET in particular, with response type 'blob')
How should I save this to chrome application's file system?
Currently using an Angular wrapper on HTML5 filesystem API
https://github.com/maciel310/angular-filesystem
I do not want to show user a popup (hence I can't use chrome.fileSystem. chooseEntry )
The chrome.fileSystem.requestFileSystem API is only supported by Kiosk-only apps.
Hence I'm using HTML5 FileSystem API instead of chrome's.
I'm using following code to make XHR to fetch blob.
$http({
url: SERVER_URL+"/someVideo.mp4",
method: "GET",
responseType: "blob"
}).then(function(response) {
console.log(response);
fileSystem.writeBlob(response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
}, function (response) {
});
This is my writeBlob method
writeBlob: function(fileName, blob, append) {
append = (typeof append == 'undefined' ? false : append);
var def = $q.defer();
fsDefer.promise.then(function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
if(append) {
fileWriter.seek(fileWriter.length);
}
var truncated = false;
fileWriter.onwriteend = function(e) {
//truncate all data after current position
if (!truncated) {
truncated = true;
this.truncate(this.position);
return;
}
safeResolve(def, "");
};
fileWriter.onerror = function(e) {
safeReject(def, {text: 'Write failed', obj: e});
};
fileWriter.write(blob);
}, function(e) {
safeReject(def, {text: "Error creating file", obj: e});
});
}, function(e) {
safeReject(def, {text: "Error getting file", obj: e});
});
}, function(err) {
def.reject(err);
});
return def.promise;
},
This shows SECURITY_ERR as It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.
What's the solution for this?
I've tried using --allow-file-access-from-files flag while launching app. It doesn't help.
Chrome Application's sandbox storage doesn't allow files to be stored in root directory (i.e. / )
Modify the code to save it in a specific sub-directory under it.
For example -
fileSystem.writeBlob("/new"+response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
This would successfully save the file under /new/ directory.
To expand on this, here is a full example app on how to download a file and save the blob and display it back to the user.
https://github.com/PierBover/chrome-os-app-download-example

Categories

Resources