I am trying to rename file using Cordova File Plugin. It gives me error with Code 1000 without any description. Here is code sample I am using
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
console.log('root url '+fileSystem.root.toURL());
var entry = new FileEntry("Download/abc.pdf");
fileSystem.root.getDirectory("Download", {create: true, exclusive: false},
function (directory) {
entry.moveTo(directory, "file.pdf", success, fail);
}, fail);
}
function success(fileEntry) {
console.log("New Path: " + fileEntry.fullPath);
}
function fail(error) {
console.log("Error: " + error);
}
I have already placed abc.pdf in Download folder.
Not sure what I am doing wrong.
I am using Cordova 4.0.0 with Android (platform version 3.4.0)
It worked but with following way,
fileSystem.root.getFile("Download/abc.pdf", {}, function(file){
fileSystem.root.getDirectory("Download", {}, function (directory) {
file.moveTo(directory, "file.pdf", success, fail);
}, function(error){
console.log(error,"Directory Error ");
});
}, function(error){
console.log(error,"File Error ");
});
I got a dirty (?) working version of same as
var entry = new FileEntry("abc.pdf");
entry.fullPath = "//Download/abc.pdf";
entry.nativeURL = fileSystem.root.toURL() + "Download/abc.pdf";
entry.filesystem = new FileSystem('persistent');
var dirEntry = new DirectoryEntry("Download");
dirEntry.fullPath = "//Download/";
dirEntry.nativeURL = fileSystem.root.toURL() + "Download/";
dirEntry.filesystem = new FileSystem('persistent');
entry.moveTo(dirEntry, "file.pdf", success, fail);
Related
Why this works :
myFile1 = "myReadme.txt";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getFile(myFile1, {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
alert("good");
}
function fail(error) {
alert("Error");
}
and that doesn't work ?
myFile2 = cordova.file.externalDataDirectory + "myReadme.txt";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getFile(myFile2, {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
alert("good");
}
function fail(error) {
alert("Error");
}
Can we not use cordova.file.dataDirectory or cordova.file.externalRootDirectory or externalDataDirectory for Android ?
Thank you
I'm gonna try to answer with this issue (but I'm sure we can to do better ? )
First, when I plug my device to my computer the tree path is about like that :
MyFile1.txt
MyApplication
MyFiles
MyCache
Application
DCIM
media
Movies
Musics
Android
data
data (I think is not accessible when your are not rooted ???)
com.MyDomainName.MyAppName
cache
files
Then,
Following this official Cordova document : http://plugins.cordova.io/#/package/org.apache.cordova.file
, My first wish is to store my files and datas with "cordova.file.dataDirectory" or "cordova.file.externalDataDirectory" or another else ... ?
when you're doing console.log(cordova.file.dataDirectory) you obtain file:///data/data/com.MyDomainName.MyAppName/files/ => This, you cannot access when you are no rooted
and when you're doing console.log(cordova.file.externalDataDirectory) you obtain
file:///storage/emulated/0/
and when you're doing that
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) { console.log(fileSystem.root) ...
you can see in this object : nativeURL: "file:///storage/emulated/0/" ... so, it's the same like "externalDataDirectory" and I suppose we cannot use "dataDirectory" ...
Anyway, I don't know whether it's the best practice but here you are my solution :
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin, getDirectoryFail);
function onFSWin(fileSystem) {
fileSystem.root.getDirectory("myFolder", {create: true, exclusive: false}, getDirectorySuccess, getDirectoryFail);
}
function getDirectorySuccess(parent) {
console.log("New Folder or Folder already exists: " + parent.fullPath);
}
function getDirectoryFail(error) {
console.log("Unable to create new directory: " + error.code);
}
// Second, we gonna check or create a new file in a specific folder
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin2, onFSFail2);
function onFSWin2(fileSystem) {
fileSystem.root.getFile("myFolder/myFile1.txt", {create: true, exclusive: false}, gotFileEntry, onFSFail2);
}
function gotFileEntry(fileEntry) {
console.log("New file: " + fileEntry.fullPath);
fileEntry.createWriter(gotFileWriter, onFSFail2);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
}
function onFSFail2(error) {
console.log(error.code);
}
You can use resolveLocalFileSystemURL to use the cordova.file.* properties:
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function (dirEntry) {
dirEntry.getFile("myFile1.txt", {
create: true,
exclusive: false
}, function (fileEntry) {
// fileEntry.createWriter
}, onError);
});
Cordova version: 3.4.1-0.1.0
I am using the file transfer plugin and I cannot save a image to file.
Errors I get from the device:
"download error target err"
upload error code 1
Here is the code, any ideas?
var fileTransfer = new FileTransfer(),
d = new Date(),
testImageUrl = encodeURI('http://www.inutritie.ro/wp-content/uploads/2013/07/otet-600x300.jpg'),
imageCacheDir = '//Testdir';
fileTransfer.download(
testImageUrl,
'file:'+imageCacheDir+'/'+d.getTime(),
function(entry){
alert("download complete: " + entry.fullPath);
},
function(error){
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
}
);
Here is how I set and get the directory where I'll save the images on my Android device:
function initLocalCacheDir(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFileSystemFail);
};
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("Testdir",{create:true, exclusive: false}, gotDir, gotDirError);
};
function gotDir(d) {
var imageCacheDir = d.fullPath;
};
function gotDirError(evt) {
alert('gotDirError');
};
function onFileSystemFail(evt) {
alert('onFileSystemFail');
};
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
//request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
}
function fileSystemSuccess(fileSystem) {
var directoryEntry = fileSystem.root; // to get root path to directory
directoryEntry.getDirectory("teste_recev", {create: true, exclusive: false}, onDirectorySuccess, onDirectoryFail);
var rootdir = fileSystem.root;
var fp = rootdir.fullPath;
fp = fp+"/teste_recev/image_name.jpg";
var fileTransfer = new FileTransfer();
fileTransfer.download("https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash3/t1.0-1/c14.4.48.48/150734_264955536974736_682293823_t.jpg",fp,
function(entry) {
alert("download complete: " + entry.fullPath);
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
}
);
}
function onDirectorySuccess(parent) {
console.log(parent);
}
function onDirectoryFail(error) {
alert("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
console.log(evt.target.error.code);
}
But have a error:
dowload error source https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash3/t1.0-1/c14.4.48.48/150734_264955536974736_682293823_t.jpg
download error target//teste_recev/image_name.jpg
upload error code1
i have, the cordova.js in project, have link for cordova.js but have this erros if someone to help, really appreciate it.
Try like this
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function gotFS(fileSystem) {
fileSystem.root.getDirectory("your dir", {create: true}, function fileSystemSuccess(fileSystem){
fileSystem.getFile("dummy.txt",{create: true,exclusive:false},function gotFileEntry(fileEntry){
var path = fileEntry.fullPath.replace("dummy.txt","");
fileEntry.remove();
var fileTransfer = new FileTransfer();
fileTransfer.download(FILE_DOWNLOAD_URL, path+""+your -savedName,function(theFile){
alert("File Downloaded Successfully " + theFile.toURI());
},function(error){
alert("File Transfer failed" + error.message);
});
},fail);
});
}, fail);
How can I create a nested directory in Phonegap with this API?
fileSystem.root.getDirectory("Android/data/com.phonegap.myapp/dir_one/dir_two/", {create:true}, gotDir, onError);
I am using Phonegap 1.8.0 in Android 2.2.
This function will help you create nested dirs.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("device is ready");
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function fail() {
console.log("failed to get filesystem");
}
function gotFS(fileSystem) {
window.FS = fileSystem;
var printDirPath = function(entry){
console.log("Dir path - " + entry.fullPath);
}
createDirectory("dhaval/android/apps", printDirPath);
createDirectory("this/is/nested/dir", printDirPath);
createDirectory("simple_dir", printDirPath);
}
function createDirectory(path, success){
var dirs = path.split("/").reverse();
var root = window.FS.root;
var createDir = function(dir){
console.log("create dir " + dir);
root.getDirectory(dir, {
create : true,
exclusive : false
}, successCB, failCB);
};
var successCB = function(entry){
console.log("dir created " + entry.fullPath);
root = entry;
if(dirs.length > 0){
createDir(dirs.pop());
}else{
console.log("all dir created");
success(entry);
}
};
var failCB = function(){
console.log("failed to create dir " + dir);
};
createDir(dirs.pop());
}
For full example check this gist
Just to add something to dhaval's function: it's not bullet proof for any browser compliant with Javascript Filesystem. If you use it with Chrome and your path is an empty string, it will fail, because apparently, with Chrome, using split() on an empty string returns a one element array, the one element being an epmty string itself, which then causes the directory creation to fail. I modified it in order to correct the problem (there also some other not related changes, for my own purposes):
function createPath(fs, path, callback) {
var dirs = path.split("/").reverse();
var root = fs.root;
var createDir = function(dir) {
if (dir.trim()!="") {
root.getDirectory(dir, {
create: true,
exclusive: false
}, success, function(dir) {
error("failed to create dir " + dir);
});
} else {
callback();
}
};
var success = function(entry) {
root = entry;
if (dirs.length > 0) {
createDir(dirs.pop());
} else {
callback();
}
};
createDir(dirs.pop());
}
This code should do what you want:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(filesys) {
filesys.root.getDirectory("story_repository", {create: true, exclusive: false}, function(dirEntry) {
dirEntry.getDirectory("dir_name", {create: true, exclusive: false}, function(dirName) {
dirName.getDirectory("img", {create: true, exclusive: false}, function(imgDir) {
console.log("img creation worked");
}, function(error) {
console.log("create img failed");
});
dirName.getDirectory("res", {create: true, exclusive: false}, function(imgDir) {
console.log("res creation worked");
}, function(error) {
console.log("create res failed");
});
}, function(error) {
console.log("create dir_name failed");
})
}, function(error) {
console.log("create story repository failed");
});
}, function(error) {
console.log("request file system failed");
});
I'm using this:
function recursiveGetFile(root, path, opts, success, fail) {
function dir(entry) {
var name = path.shift();
if (path.length > 0)
entry.getDirectory(name, opts, dir, fail);
else
entry.getFile(name, opts, success, fail);
}
path = path.split('/');
dir(root);
}, fail);
There is a simple file manager for cordova-phoengap, with with you can do this and much more:
https://github.com/torrmal/cordova-simplefilemanagement
You can recursively create directories:
//CREATE A DIRECTORY RECURSIVELY as simple as:
new DirManager().create_r('folder_a/folder_b',Log('created successfully'));
Let me know if it helps
I wrote an jQuery Mobile app and packaged it with Phonegap to iOS and Android apps.
At this point I am using locally stored json files to read data.
I would like to update these json files from time to time by downloading newer json files from a server.
How can I get the json from the server and store the json files to the local file system of Android and iOS?
Cheers
Johe
Use FileTransfer.download, here is an example:
function downloadFile(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html","");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);
};
}
This is how I solved it. First set the file paths, wich are different for Android and iOS
var file_path;
function setFilePath() {
if(detectAndroid()) {
file_path = "file:///android_asset/www/res/db/";
//4 Android
} else {
file_path = "res//db//";
//4 apache//iOS/desktop
}
}
Then I load my JSON files, wich are prepackaged with the app, into the local browser storage. Like this:
localStorage["my_json_data"] = loadJSON(file_path + "my_json_data.json");
function loadJSON(url) {
return jQuery.ajax({
url : url,
async : false,
dataType : 'json'
}).responseText;
}
If I wanna update my data. I get the new JSON Data from the server and push it into the local storage. If the server is on a different domain, which is the case most of the time, you have to make a JSONP call (check jQuery's docs on JSONP).
I did it kinda like this:
$.getJSON(my_host + 'json.php?function=' + my_json_function + '&callback=?', function (json_data) {
//write to local storage
localStorage["my_json_data"] = JSON.stringify(json_data);
});
You can do this in one line of code:
new FileManager().download_file('http://url','target_path',Log('downloaded success'));
target_path: can include directory (example: dira/dirb/file.html) and the directories will be created recursively.
You can find the library to do this here:
https://github.com/torrmal/cordova-simplefilemanagement
My suggestion would be to look into PhoneGap's File API. I haven't used it myself, but it should do what you're after.
Updated Answer for new Cordova
function downloadFile(url, filename, callback, callback_error) {
var fileTransfer = new FileTransfer();
fileTransfer.download(url,
cordova.file.dataDirectory + "cache/" + filename,
function (theFile) {
console.log("download complete: " + theFile.toURL());
if (callback)
callback();
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
if (callback_error)
callback_error();
}
);
}
For downloading and displaying a file, follow the sample code.
Include the given code just above the </head> tag in your index.html
< script type = "text/javascript" charset = "utf-8" >
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
alert("Going to start download");
downloadFile();
}
function downloadFile() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {
create: true,
exclusive: false
},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
},
fail);
},
fail);
}
function showLink(url) {
alert(url);
var divEl = document.getElementById("deviceready");
var aElem = document.createElement("a");
aElem.setAttribute("target", "_blank");
aElem.setAttribute("href", url);
aElem.appendChild(document.createTextNode("Ready! Click To Open."))
divEl.appendChild(aElem);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
Refer :- Blog Post