I am building up a basic app which features PhoneGap pretty heavily as i am trying to determine what it can/can't do. i have gotten to the stage where i am looking to remove a file that has been downloaded on the app, but it won't work. most of the code i've used is from http://docs.phonegap.com/en/2.4.0/cordova_file_file.md.html#FileEntry;
function removefile(){
fileSystem.root.getFile("readme.txt", {create: false, exclusive: false}, gotRemoveFileEntry, fail);
}
function gotRemoveFileEntry(fileEntry){
console.log(fileEntry);
fileEntry.file(gotFile, fail);
entry.remove(success, fail);
}
function success(entry) {
console.log("Removal succeeded");
}
function fail(error) {
console.log("Error removing file: " + error.code);
}
and i have called it using the HTML;
<button onclick="removefile();">remove file</button>
is there something wrong with the code? i can't see it.
By the way I'm coding for iOS and using JavaScript, HTML and PhoneGap/Cordova in Xcode.
I'm fairly new to iPhone development so any help would be great thanks a lot :)
Your code is slightly off. Try:
function removefile(){
fileSystem.root.getFile("readme.txt", {create: false, exclusive: false}, gotRemoveFileEntry, fail);
}
function gotRemoveFileEntry(fileEntry){
console.log(fileEntry);
fileEntry.remove(success, fail);
}
function success(entry) {
console.log("Removal succeeded");
}
function fail(error) {
console.log("Error removing file: " + error.code);
}
Old entry. The API may have changed, but I was able to do it like this:
function success(entry) {
console.log("Removal succeeded");
}
function fail(error) {
console.log("Error removing file: " + error.code);
}
resolveLocalFileSystemURL(cordova.file.dataDirectory + 'assets/icons/test.png', function(entry) {
console.log(entry);
entry.remove(success, fail);
})
Related
I'm trying to create a excel on a mobile device, I'm testing with android but it should work for iOS too
I used the following code from the documentation
Documentation
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
console.log('file system open: ' + fs.name);
fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {
console.log("fileEntry is file?" + fileEntry.isFile.toString());
fileEntry.name == 'someFile.txt'
fileEntry.fullPath == '/someFile.txt'
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
console.log("Successful file read: " + this.result);
//displayFileData(fileEntry.fullPath + ": " + this.result);
};
reader.readAsText(file);
},);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
let dataObj = new Blob(['some file data'], { type: 'text/plain' });
fileWriter.write(dataObj);
});
});
});
I've tried changing the first three lines for the following ones, with the same result
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (fs) {
console.log('file system open: ' + fs.name);
fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) { ...
I get the following console log
file system open: persistent
fileEntry is file?true
Successful file write...
Successful file read: some file data
so, the file is created and I can read it, but I don't get any prompt or something, then I navigate to my file on Android/data/com.myapp.app/files and I don't have any file
Seems the files were saving but I couldn't see them, but I could read them via cordova-file-plugin
I changed the destination folder to
let ruta = cordova.file.externalRootDirectory
let directoryRoute = "myApp";
window.resolveLocalFileSystemURL(ruta, function (fs) {
fs.getDirectory(directoryRoute, { create: true }, function (fs2) {
fs2.getFile(fileName, { create: true, exclusive: false }
, function (fileEntry) { ...
with cordova.file.externalRootDirectory I'm creating if doesn't exist a folder to save my app documents, this works with android, probably there will be changes to iOS
I'm going to update the answer on a few days when I have the answer for iOS in case this can help someone
I'm currently creating text files with code similar to the following. This will create a file just fine, but it won't delete an existing file.
fs.root.getFile('log.txt', {create: true, exclusive: false},
function(fileentry) {
fileentry.createWriter(function (filewriter) {
filewriter.write('Hello world!');
});
}
);
Any way of deleting an existing file cleanly without too much extra code or dedicated deletion code?
I've been using this guide but with no luck finding an efficient way of doing this.
http://www.html5rocks.com/en/tutorials/file/filesystem/
This is as close as I can get. It checks for the file, removes if it's there. It also captures the error if it cannot be removed. If by the end of all that, there is space for the new file, it is created as before.
fs.root.getFile('log.txt', {create: false},
function(fileentry) {
fileentry.remove(createfile, errorhandler);
},
createfile
);
function createfile(){
//either the file was never there or has been removed successfully
fs.root.getFile('log.txt', {create: true, exclusive: false},
function(fileentry) {
fileentry.createWriter(function (filewriter) {
filewriter.write('Hello world!');
});
}
);
}
function errorhandler(error){
//file already exists and couldn't be removed
}
It's not as compact nor and pretty as I'd have liked, but it's the best I can come up with for now.
This should work much like your writer does:
fs.root.getFile('log.txt', {create: false}, function(fileEntry) {
fileEntry.remove(function() {
console.log('File deleted.');
}, errorHandler);
}, errorHandler);
I am trying to remove a file from an SD card using phonegap build but I can't. I think my code have some problem, Its not getting entered into the gotRemoveFileEntry function. Whats the problem?
Here is my code:
function removefile(){
fileSystem.root.getFile("readme.txt", {create: false, exclusive: false}, gotRemoveFileEntry, fail);
}
function gotRemoveFileEntry(fileEntry){
console.log(fileEntry);
fileEntry.remove(success, fail);
}
function success(entry) {
console.log("Removal succeeded");
}
function fail(error) {
console.log("Error removing file: " + error.code);
}
Please anybody help me to remove a created file.
I am using Cordova 2.5.0.
I have tried this, but it didn't satisfy my request at all. I write a new one:
var file_system;
var fs_root;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024*1024, onInitFs, request_FS_fail);
function onInitFs(fs) {
file_system= fs;
fs_root= file_system.root;
alert("ini fs");
create_Directory();
alert("ini fs done.");
}
var string_array;
var main_dir= "story_repository/"+ User_Editime;
string_array= new Array("story_repository/",main_dir, main_dir+"/rec", main_dir+"/img","story_repository/"+ User_Name );
function create_Directory(){
var start= 0;
var path="";
while(start < string_array.length) {
path = string_array[start];
alert(start+" th created directory " +" is "+ path);
fs_root.getDirectory(
path,
{create: true, exclusive: false},
function(entry) {
alert(path +"is created.");
},
create_dir_err()
);
start++;
}//while loop
}//create_Directory
function create_dir_err() {
alert("Recursively create directories error.");
}
function request_FS_fail() {
alert("Failed to request File System ");
}
Although the directories are created, the it sends me
ErrorCallback:"alert("Recursively create directories error.");"
First, I don't think this code will work since I have tried this, which failed:
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
//request file system success callback.
function(fileSys) {
fileSys.root.getDirectory(
"story_repository/"+ dir_name,
{create: true, exclusive: false},
//Create directory story_repository/Stallman_time.
function(directory) {
alert("Create directory: "+ "story_repository/"+ dir_name);
//create dir_name/img/
fileSys.root.getDirectory {
"story_repository/"+ dir_name + "/img/",
{create: true, exclusive: false},
function(directory) {
alert("Create a directory: "+ "story_repository/"+ dir_name + "/img/");
//check.
//create dir_name/rec/
fileSys.root.getDirectory {
"story_repository/"+ dir_name + "/rec/",
{create: true, exclusive: false},
function(directory) {
alert("Create a directory: "+ "story_repository/"+ dir_name + "/rec/");
//check.
//Go ahead.
},
createError
}
//create dir_name/rec/
},
createError
}
//create dir_name/img
},
createError
);
},
//Create directory story_repository/Stallman_time.
createError());
}
I just repeatedly call fs.root.getDirectory only but it failed. But the first one is almost the same...
What is the problem at all? Why does the first one always gives me the ErrorCallback?
Why can't the second one work?
Does anyone has a better solution? (no ErrorcallBack msg)
ps: I work on Android and PhoneGap 1.7.0.
I am not able to figure out mistake in your code. I have a library written to do localIO via PhoneGap 2.0. I have abstracted code for your requirements from there. See if it works for 1.7. I have not tested the code after abstraction. You may need to fix error, if any.
var fsroot = fs.root; // initialize this
function fileGetDir(path, cb) {
var fnGetOrCreateDir = function(p, de) {
var entry = p.shift();
if (entry) {
de.getDirectory(entry, {
create : true
}, function(dirEntry) {
fnGetOrCreateDir(p, dirEntry);
}, fileFSError);
}
else
if (cb) cb(de);
};
if (path) {
var arPath = path.split("/");
fnGetOrCreateDir(arPath, fsroot);
}
else {
if (cb) cb(fsroot);
}
}
function fileFSError(e) {
console.log(e.code);
try {
console.log("fileFSError: " + JSON.stringify(e));
} catch (err) {}
}
function printSuccess(dirEntry) {
console.log(dirEntry.fullPath);
}
// Now create your directories like:
var main_dir= "story_repository/"+ User_Editime;
fileGetDir(mainDir + "/rec", printSuccess);
fileGetDir(mainDir + "/img", printSuccess);
fileGetDir("story_repository/"+ User_Name, printSuccess);
There is a simple file manager for cordova-phoengap:
https://github.com/torrmal/cordova-simplefilemanagement
You can recursively create directories:
//CREATE A DIRECTORY RECURSIVELY
var a = new DirManager(); // Initialize a Folder manager
a.create_r('folder_a/folder_b',Log('created successfully'));
If the first directory off the root "story_repository" does not exist your first call to getDirectory will call the error callback because the call to create dir_name in a non-existent directory will error out on the native side.
Does "story_repository" exist?
I tried a simple project using HTML5 FileSystem,
so I can store data in the client-side.
My first trial was a success, because I initiate everything at the start with JavaScript,
and manipulate the file (read the file and append it to the textarea or P; and write/modify the file) in the onclick or onkeypress event.
But, when I do it simultaneously outside of the event, the variable of the filesystem is null/undefined and I can't continue the process.
Here is the code which is working fine:
function initFS() {
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,
function(grantedBytes) {
window.requestFileSystem(window.TEMPORARY, grantedBytes, function (filesystem)
{
fs = filesystem;
}, errorHandler);
});
}
document.body.onclick=function()
{
alert(fs);
fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
}, errorHandler);
}
The alert(fs) resulted in DOM FileSystem and that means that the fs variable is the FileSystem.
But when I do this:
function initFS()
{
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,function(grantedBytes){
window.requestFileSystem(window.TEMPORARY, grantedBytes, function(filesystem) {
fs = filesystem;
}, errorHandler);
})
}
if (window.requestFileSystem) {
initFS();
}
alert(fs);
the alert(fs) returned null.
Is there any solution that can be done to this? Any explanation would be useful for this.
My last resort would be add a button so that after the click the fs will definitely be a filesystem, but I try to avoid that method.
It's probably because requestQuota and requestFileSystem functions are asynchronous. In other words, the alert() is being executed before fs is set.
So.. you could put all the code in the requestFileSystem callback? I'm unclear on what you are trying to achieve
For example you could do:
function initFS(callback)
{
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,function(grantedBytes){
window.requestFileSystem(window.TEMPORARY, grantedBytes, function(filesystem) {
callback(filesystem)
}, errorHandler);
})
}
if (window.requestFileSystem) {
initFS(function (fs) {
alert(fs)
});
}