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?
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 am working in UI automation testing project i need to send a ajax request to my server but in Nighwatch.js some functions of vanilla javascript and JQuery functions are not acceptable,
so if anyone has any experience to send Ajax get request to server in nightwatch.js environment then please give me some info/suggestions.
After long research i found request.js a node module, I have resolved my issue by installing "request" node module. After installing i am able to perform "GET" and "POST" requests to my servers within Nightwatch environment. I am writing piece of code which working like a charm.
/* jshint expr: true */
module.exports = {
'#tags' : ['book'],
beforeEach : function (client) {
},
after : function (client) {
client.end();
},
wGroup: {
book_url: "https://example.myApi.mycompany.in"
},
userSettings: Array(),
"Get all settings": function (client, done) {
var widget = this.wGroup;
client.getreq( widget.book_url + "/api/store", widget, function (response) {
client.assert.equal(response.statusCode, 200, "201 Created");
var objects = response.body.objects;
client.userSettings = objects;
console.log( 'Found number of settings: ' + client.userSettings.length );
client.end();
});
},
"Remove settings": function (client, done) {
var widget = this.wGroup;
var objects = client.userSettings;
for( i=0; i<objects.length; i++ ) {
var obj = objects[i];
console.log('Removing user settings id ' + obj.id );
client.deletereq( widget.book_url: l + "/api/store" + obj.id, widget, function (resp) {
client.assert.equal(resp.statusCode, 204, "204 Created");
client.end();
});
}
},
};
Ho to everyone. I followed this tutorial to create a modal view with a pdf generated with pdfmake.
http://gonehybrid.com/how-to-create-and-display-a-pdf-file-in-your-ionic-app/
My simply question is how can i save the pdf in my local storage on in cache? I need that to send the pdf by email or open it with openfile2. I'm using Ionic and cordova.
I don't know how you code it, but I know what plugin you should use:
https://github.com/apache/cordova-plugin-file
The git contains a complete documentation of the plugin so everything you could need should be there.
Sample code to write pdf file in device using cordova file and file transfer plugin:
var fileTransfer = new FileTransfer();
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
// for iOS
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}
function onError(e) {
navigator.notification.alert("Error : Downloading Failed");
};
function onFileSystemSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("Cordova", {
create: true,
exclusive: false
}, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
cdr = dir;
dir.getFile(filename, {
create: true,
exclusive: false
}, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
// URL in which the pdf is available
var documentUrl = "http://localhost:8080/testapp/test.pdf";
var uri = encodeURI(documentUrl);
fileTransfer.download(uri, cdr.nativeURL + "test.pdf",
function(entry) {
// Logic to open file using file opener plugin
},
function(error) {
navigator.notification.alert(ajaxErrorMsg);
},
false
);
};
I would like to set the request endpoint of fine-uploader dynamically.
For example:
$('#jquery-wrapped-fine-uploader').fineUploader({
request: {
endpoint: submitUrl
},
multiple: false,
button: $("#uploader-button"),
// etc...
});
submitUrl must be already set in the page and can't be changed.
I would like to do something more dynamic, something like:
request: {
endpoint: function() { ($('#submitUrlField').val() }
}
But the above sends the request to
function%20()%20%7B%20$(%27#submitUrlField%27).val()%20}
Grateful for anyone who knows how to do this!
You can use multi enpoints.
For example use several endpoint for odd/even uploads:
callbacks: {
onUpload: function(id, name) {
var endpoint = endpoints[id % endpoints.length];
this.setEndpoint(endpoint.url, id);
this.setParams({
signature: endpoint.signature,
params: endpoint.params,
ajax: true
}, id);
}
}
If the file is big and you have enabled the chunking, you can't change the endpoint url dinamically.
My solution is use the event
callbacks:{
onComplete:function(id,name,responseJSON,xhr) {
console.log('> onComplete. id=' + id);
console.log('> onComplete. name=' + name);
console.log('> onComplete. responseJSON=' + JSON.stringify(responseJSON));
console.log('> onComplete. uuid=' + responseJSON.uuid);
if (responseJSON.success)
{
// call a httpRequest with the url you want.
}
}
}
One useful example for the setEndpoint method. This code will set endpoint based on uploading file type:
callbacks: {
onUpload: function(id, name) {
var file = this.getFile(id);
var fileType = file.type;
this.setEndpoint(endpointList[fileType], id);
}
}
Your endpointList:
var endpointList = {
'image/png': 'url/uploadimage',
'video/mp4': 'url/uploadvideo',
'text/plain': 'url/uploadtext'
}
your old code:
request: {
endpoint: function() { ($('#submitUrlField').val() }
}
|_ why need ( becasue it has not close ) match
try one of these
request: {
endpoint: function() { return $('#submitUrlField').val() } // here you had `(`
}
or
request: {
endpoint: $('#submitUrlField').val()
}
I know that we can create a single directory in phonegap using the following code:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);
function onRequestFileSystemSuccess(fileSystem) {
var entry=fileSystem.root;
entry.getDirectory("Folder1", {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
}
function onGetDirectorySuccess(dir) {
console.log("Created dir "+dir.name);
}
function onGetDirectoryFail(error) {
console.log("Error creating directory "+error.code);
}
This would create a single folder "Folder1" if it does not exist.
My question is how would you create an entire directory tree at once??
ex. Folder1/Folder2