A few folks have asked “how do I simply rename a local file in Cordova?” Well, to start, you’ll need the file plugin from Apache Cordova. If you don’t already have this, run the below to add the file plugin.
cordova plugin add org.apache.cordova.core.file
Then, you can use the “moveTo” function to rename the file. Below is a reusable function I utilize to pass the current file name, directory, the new file name and a function that happens when the rename is successful.
You can utilize the below function like:
//to call the function. 'renameSuccess' is an function that is used as the success event if the rename is okay renameFile('somefile.xml','myapp/xml/','new.xml', renameSuccess); //the function function renameFile(currentName, currentDir, newName, successFunction) { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(currentDir + currentName, null, function (fileEntry) { fileSystem.root.getDirectory(currentDir, {create: true}, function (dirEntry) { parentEntry = new DirectoryEntry(currentName, currentDir + currentName); fileEntry.moveTo(dirEntry, newName, function () { successFunction(); }, renameFail); }, renameFail); }, renameFail); }, renameFail); } //and the sample success function function renameSuccess() { alert('renamed!'); } //and the sample fail function function renameFail() { alert('failed'); }
I’m not saying this is the ‘best’ way to do this, so feel free to comment on improvements!
HI thanks for the code….but it is not working…can you say any suggestions…for the renameFile function i have passesd on the argument s from variables
LikeLike