Access to a directory in Cordova - android

I'm writing a simple File Explorer application, This is what I have done so far:
$window.requestFileSystem($window.LocalFileSystem.PERSISTENT, 0, function(fs) {
console.log("fs", fs);
var directoryReader = fs.root.createReader();
directoryReader.readEntries(function(entries) {
var arr = [];
processEntries(entries, arr); // arr is pass by refrence
$scope.files = arr;
// $rootScope.hide();
},
function(error) {
console.log(error);
});
},
function(error) {
console.log(error);
});
The result of the above code just only allow me to access to the root directory of my phone. However, I want to access to the specific folders in my phone. For example, I want to open the 'Download' folder everytime I open the app. How can I get it to be done. Please help :(

You maybe need to use window.resolveLocalFileSystemURL(pathToYourDownloadDir) ?
and be sure your are permission to acces file system

Related

Cordova - Save a file to storage

I am making a Cordova application from which I need to export a file. I would like to save the file to the Android device's storage: /storage/emulated/0/. The app should create a folder in which it will create a file with content in it.
I tried the cordova-plugin-file plugin but I'm not sure how to use it. There are examples on the plugin's documentation but I don't know which one to use, there is:
Create a persistent file
Write to a file
Append a file using alternative methods
And I tried them all however none of them works.
Your help and an example (if possible) would be greatly appreciated.
EDIT
There's the code I used. I'm not getting any error.
function createFile(dirEntry, fileName, fileContent, isAppend) {
dirEntry.getFile(fileName, {create: true, exclusive: false}, function(fileEntry) {
writeFile(fileEntry, fileContent, isAppend);
}, fail);
}
function savePasswords(fileSystem) {
createFile("/sdcard/testFolder", "testfile.txt", "TEST", true);
}
function fail(error) {
alert("ERROR: " + error.code);
}
function request() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, savePasswords, fail);
}
document.addEventListener("deviceready", request, false);
I want this to create the file "testfile.txt" with content "TEST" in a folder named "testFolder".
This script works:
function writeFile(fileEntry, dataObj) {
// 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(["Content if there's nothing!"], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
}
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (rootDirEntry) {
rootDirEntry.getDirectory(fileDir, { create: true }, function (dirEntry) {
var isAppend = true;
dirEntry.getFile(fileName, { create: true }, function (fileEntry) {
writeFile(fileEntry, "Content!", isAppend);
// Success
});
});
});
Since Android 4.4, the SD card root (/sdcard/) is read-only so you cannot write to it. Assuming your reference to writeFile() in your example code refers to the cordova-plugin-file example (since it's not defined in your code), then the fileWriter.onerror() function would be invoked with error code NO_MODIFICATION_ALLOWED_ERR.
You must write to the application storage directory on the SD card (e.g. /sdcard/Android/data/your.app.package.id/).
You can reference this location using cordova-plugin-file as cordova.file.externalApplicationStorageDirectory.
See this answer for details of SD card access in different versions of Android.
Note: above references to "SD card" refer to the emulated SD card (on internal memory (i.e. /storage/emulated/0/). Referencing the external/removable SD card present in some Android devices (e.g. Samsung Galaxy S range) is not possible via cordova-plugin-file, however you can use getExternalSdCardDetails() from cordova-diagnostic-plugin to do so.

How to write to a text file in a specific path in android device

I am using visual studio to create cordova mobile application and I'm using Cordova-plugin-file for file manipulation on device.
How to write to a text file in a specific path in android device,
to be able to get it from a fixed location.
You can try below code. Also you can find good explanation for the code in Cordova Example: Writing to a file & Exploring the FileSystem APIs.
As a very short explanation: you should install cordova file plugin, after device ready, you first will ask for a FileSystem then will create the file in a particular path (in my example:cordova.file.dataDirectory) and finally will write to it.
document.addEventListener('deviceready', function () {
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) {
dirEntry.getFile("log.txt", { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
console.log('Write completed.');
};
fileWriter.onerror = function (e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var blob = new Blob(['Lorem Ipsum'], { type: 'text/plain' });
fileWriter.write(blob);
}, errorHandler);
});
});
}, false);

Create a directory in internal storage of device in PhoneGap

I want to create a folder in the internal storage of my device, but not in the root directory, which will store the audios I've recorded using my app. I've tried using the following code to implement the same:
fileSys.root.getDirectory('file:///storage/sdcard/records', {create: true, exclusive: false},function(d) {
window.resolveLocalFileSystemURL($scope.sound.file, function(fe) {
fe.copyTo(d, filename, function(e) {
console.log('success in copy');
console.dir(e);
$scope.sound.file = e.nativeURL;
$scope.sound.path = e.fullPath;
}, function(e) {
console.log('error in copy');console.dir(e);
});
}, function(e) {
console.log("error in directory");
console.dir(e);
});
}, function(e) {
console.log("error in file");
console.dir(e);
});
But an error(code = 5) is generated when I implement the above code. Can someone point out the error in the above code so the directory is created and file is copied to the specified location?
I had the same issue and I preferred to use https://github.com/torrmal/cordova-simplefilemanagement which wraps native storage api.
Then you can do something like this:
var a = new DirManager(); // Initialize a Folder manager IF does not exists
a.create_r("NewFolder", function () {/* Notify dir creation*/ });

Cannot open files with FileOpener2, but not getting an error in Android

I am attempting to open a PDF file with FileOpener2 (through ng-cordova) with the following code:
$cordovaFile.checkFile(cordova.file.dataDirectory, attachmentPath)
.then((fileEntry) => {
// success
fileEntry.getMetadata((metadata) => {
// metadata.size is in bytes
var megabyteSize = metadata.size / 1048576;
if (megabyteSize > 5) {
var path = cordova.file.dataDirectory + attachmentPath;
console.log(path); // prints: file:///data/data/com.ionicframework.enhatch146189/files/attachments/CS-353ES_CS-420ES_Eng.pdf which is correct
$cordovaFileOpener2.open(path, 'application/pdf').then(() => {
console.log("Opened!") // prints
}, (error) => {
console.log(error);
usePDFJs(); // tries to render PDF in app with PDFJs
});
} else {
usePDFJs();
}
})
}, function (error) {
// error
console.error(error);
});
What happens confuses me: it prompts me with an "open this file in Adobe Reader?" and lists the other PDF viewers, and the console prints "Opened!"
However, no matter what I open ANY pdf in, I get some sort of error such as "cannot open this PDF file".
Can anyone see something wrong with this code?
Apparently, if you use cordova.file.dataDirectory on android you can't open those files in other applications or attach them to emails. Silly mistake -- coded too fast and read too little on the documentation. Using cordova.file.externalApplicationStorageDirectory solved the issue.

List files on directory on phonegap build

Hi im currently trying to create an gallery app with phonegap build, but i cant read files from the local storage. I`m using this function:
function listDir(directoryEntry){
var directoryReader = directoryEntry.createReader();
directoryReader.readEntries(function(entries){ // success get files and folders
for(var i=0; i<entries.length; ++i){
alert(entries[i].name) // this is just for checking purposes, no matter what i put here it wont fire
}
}, function(error){ // error get files and folders
alert(error.code);
});
}
function getFileSystem(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){ // success get file system
var sdcard = fileSystem.root;
sdcard.getDirectory('dcim',{create:false}, function(dirEntry){
listDir(dirEntry);
}, function(error){
alert(error.code);
})
}, function(evt){ // error get file system
console.log(evt.target.error.code);
});
}
getFileSystem();
The listDir function wont even fire (the error function wont too). I have tried to add an "OnDeviceReady" listener to call the getFileSystem() function but it wont work too, plus i have tried toons of ways, even using the official phonegap docs, but it cant read my directory. Anyone know how to do this (im currently using android)? Thanks in advance.
You need remember that the cordova api is async.
This code read the list of files in my app external storage directory:
function getFilesList(callback) {
console.log('getFilesList');
var fileList = [];
function onDirResolved(dir) {
var reader =dir.createReader();
reader.readEntries(function(entries) {
console.log('readEntries');
for (var i=0; i<entries.length; i++) {
if (entries[i].name.indexOf(".fototoon") != -1) {
fileList.push(entries[i].fullPath);
};
};
console.log('fileList ' + fileList);
callback(fileList);
}, errorHandler);
};
function onFsResolved(fs) {
window.resolveLocalFileSystemURL(
cordova.file.externalApplicationStorageDirectory,
onDirResolved, errorHandler);
};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
onFsResolved, errorHandler);
};
The callback function will receive the list of files read.

Categories

Resources