directory is not created using phonegap android - android

Having problem with creating directories,here's my code:
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "myFolder";
var newFile=myFolderApp+"/"+newFileName;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
alert('root is :'+fileSys.root.name)
fileSys.root.getDirectory("myFolder",{create:true, exclusive: false},
function(directory)
{
alert('direcrory name :'+directory.name)
fileSystem.copyTo(directory, newFileName,function(fileSystem)
{
alert('file sved!')
}, resOnError);
},
resOnError);
},
resOnError);
function resOnError(error) {
alert('Error at resOnError :'+error.code+' ,message :'+eror.message);
}
Also added both permissions for read and write.
this is the plugin "cordova plugin add cordova-plugin-file" used.
calling this function via another function,not using device ready event.
3.directory is not created and code execute with no error.
Thanks
HERE's Code
var pictureSource; // picture source
var destinationType; // sets the format of returned value
(function(){
document.addEventListener("deviceready", onDeviceReady, false);
})();
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function save()
{
alert(imageForCategory)
window.resolveLocalFileSystemURL(imageForCategory,resolveOnSuccess,resOnError);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 100,destinationType: destinationType.FILE_URI,sourceType: source });
}
var imageForCategory="";
function onPhotoURISuccess(imageURI)
{
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
imageForCategory=largeImage.src;
}
function resOnError(error) {
alert('Error at resOnError :'+error.code+' ,message :'+error.message);
}
function resolveOnSuccess(fileSystem)
{
alert('on resolve success called');
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "myFolder";
var newFile = myFolderApp + "/" + newFileName;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSys) {
alert('root is :' + fileSys.root.name);
fileSys.root.getDirectory("myFolder", {create: true, exclusive: false},
function (directory) {
alert('directory name :' + directory.name);
directory.getFile(newFileName, {create: true}, function (file) {
alert("File created.");
});
}, resOnError);
}, resOnError);
}

I don't know what you exactly want to do. It seams that you want to copy a file, but you don't tell something about the source.
If you want to create a file, then use this code:
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "myFolder";
var newFile = myFolderApp + "/" + newFileName;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSys) {
alert('root is :' + fileSys.root.name);
fileSys.root.getDirectory("myFolder", {create: true, exclusive: false},
function (directory) {
alert('directory name :' + directory.name);
directory.getFile(newFileName, {create: true}, function (file) {
alert("File created.");
});
}, resOnError);
}, resOnError);
function resOnError(error) {
alert('Error at resOnError :' + error.code + ' ,message :' + eror.message);
}

Related

Error 5 getting directory when i take photo in Cordova app

I am getting photos, and i want to show them (it works) and save them on my directory. I followed mixed responses from this forum and w3c to obtain this code. My problem is when im getting the fileSys directory, it goes to onError, it cant get myFolderApp directory. Monitor shows "
Failed to ensure directory:
/storage/sdcard1/Android/data/tta.kirolapp.v1/files
and
Failed to ensure directory:
/storage/sdcard1/Android/data/tta.kirolapp.v1/files
This is normal because the app default directory is
/storage/emulated/0/0Android/data/tta.kirolapp.v1/
so, i think this is the problem but i don't know how to fix it.
The code of the functions which takes the photo and manage it, is the next:
function capturePhoto() {
alert('on capturePhoto');
sessionStorage.removeItem('imagepath');
//Cogemos la imagen y la codificamos en Base64
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, cameraDirection: 1, saveToPhotoAlbum:true, destinationType: Camera.DestinationType.FILE_URI });
}
function onPhotoDataSuccess(imageURI) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var imgProfile = document.getElementById('fotoRegistro');
// Pasamos la imagen a pantalla desde imageURI
//
console.log('El url por defecto es: '+ imageURI);
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1){
getLocation();
}
movePic(imageURI);
}
// Funcion onError
//
function onFail(message) {
alert('Failed because: ' + message);
}
function movePic(file){
window.resolveLocalFileSystemURL(file, resolveOnSuccess, resOnError);
}
//Callback function when the file system uri has been resolved
function resolveOnSuccess(entry){
console.log("Estoy en resolveOnSuccess");
var d = new Date();
var n = d.getTime();
//new file name
var identificacion= $('#idEmailReg').val();
var newFileName="foto"+identificacion+".jpg";
console.log ('El newFileName es: '+ newFileName);
var myFolderApp = "file:///storage/emulated/0/Android/data/tta.kirolapp.v1/img/";
//appConstants.localPermanentStorageFolderImg;
console.log ('El nuevo directorio es: '+ myFolderApp);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
console.log ('Entramos en el request onSuccess');
//The folder is created if doesn't exist
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory) {
console.log('El directory es: '+ directory);
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
//Callback function when the file has been moved successfully - inserting the complete path
function successMove(entry) {
//Store imagepath in session for future use
// like to store it in database
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error) {
alert(error.code);
}
resOnError shows code "5", and the monitor output is the next:
I use the media plugin and take the photos with photo capturing, this is the code:
function capturePhoto(){
//var fileFolder="/storage/emulated/0/KirolApp/img/";
var fileFolder=appConstants.localPermanentStorageFolderImg();
var identificacion= $('#idEmailReg').val();
var fileName="foto"+identificacion+".jpg";
photo.takeAsync(
fileFolder,
fileName,
function() {
console.log('En capturePhoto funcion');
var urlCompleta=photo.fileFolder+photo.fileName;
console.log('URL Completa: '+ urlCompleta);
$("#fotoRegistro").attr("src","file://"+urlCompleta+"?"+(new Date()).getTime());
}
);
}
On my objects.js file:
var photo = {
fileFolder:null,
fileName:null,
takeAsync: function(fileFolder,fileName,onSuccess) {
navigator.device.capture.captureImage(
function(photoFiles) {
var tempFullPath=photoFiles[0].fullPath;
tempFullPath=tempFullPath.substring(tempFullPath.indexOf("/"));
alert("New photo in: "+tempFullPath);
fileUtilities.moveAsync(tempFullPath,fileFolder,fileName,
function() {
photo.fileFolder=fileFolder;
photo.fileName=fileName;
if(onSuccess!=false)
onSuccess();
}
);
},
function(error) {
var msgText = "Photo error: " + error.message + "(" + error.code + ")";
alert(msgText);
}
);
}
};
And fileUtilities:
var fileUtilities = {
moveAsync: function (sourceFullPath,destFolder,destName,onSuccess){
var url="file://"+sourceFullPath;
var destFile=destFolder+destName;
var ft=new FileTransfer();
ft.download(url,destFile,
function() {
window.resolveLocalFileSystemURL(url,
function(fileEntry) {
fileEntry.remove(onSuccess);
},
function(error) {
alert("Source file NOT accesible; not removed");
}
);
},
function(error) {
alert('File not copied. '+'error.code: '+error.code+'\nerror.source: '+error.source+'\nerror.target: '+error.target+'\nerror.http_status: '+error.http_status);
}
);
}
};
Thanks to M.H and G.P from UPV/EHU.

How to download music that stored in http server in Angularjs

Let's say I have a API that stores some .mp3 music.
The sample link here:
https://118.69.201.34:8882/api/ApiMusic/Download?songId=2000
Now I want to write an API calling function in Angularjs to download the music to my Android devices with the song's Id number as in the link.
How can I do that? Please help :(
You can use the ngCordova FileTransfer library here: http://ngcordova.com/docs/plugins/fileTransfer/
Here's example code from that page, tweaked to your example URL:
document.addEventListener('deviceready', function () {
var fileid = "2000";
var url = "https://118.69.201.34:8882/api/ApiMusic/Download?songId=" + fileid;
var targetPath = cordova.file.documentsDirectory + fileid + ".mp3";
var trustHosts = true
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
}, function(err) {
// Error
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}, false);
I did it finally, here is my code. Just share for those who want to refer to this issue in the future. Thanks you guys for your answers
$scope.download = function(songId, songName) {
$ionicLoading.show({
template: 'Downloading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getDirectory(
"fMusic",
{
create: true
},
function (dirEntry) {
dirEntry.getFile(
songName + ".mp3",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI(APIUrl + songId),
p,
function (entry) {
$ionicLoading.hide();
$scope.mp3File = entry.toURL();
},
function (error) {
$ionicLoading.hide();
alert("Download Error Source --> " + error.source);
},
false,
null
);
},
function () {
$ionicLoading.hide();
console.log("Get the file failed");
}
);
}
);
},
function () {
$ionicLoading.hide();
console.log("Request for filesystem failed");
});
}

Get the file name and the extension while uploading file in PhoneGap

I am uploding an image from a gallery using PhoneGap in Android but what I want to do is to fetch the file name and its extension which i am not be able to get it from imageuri so can any one tell me how can I find one
my imageURI is content://media/external/images/media/876 so is there a way to get a fileEntry by using this imageURI and read the file name and extension ?
function fileUpload(){
navigator.camera.getPicture(
uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality : 50,
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="uploaded_file";
alert(imageURI);
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://www.mydomain.com/mobile_upload.php"), win, fail, options);
}
function win(r) {
alert("WIN" +r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("error");
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
i found the answer and here is the code
window.resolveLocalFileSystemURI(imageURI, function(entry){
console.log("****************HERE YOU WILL GET THE NAME AND OTHER PROPERTIES***********************");
console.log(entry.name + " " +entry.fullPath);
}, function(e){
});
I had the same problem and think that I found a solution. I think it is not the best, but possible ;-)
After get File_URI from camera resolve File system from File_URI and in this fileEntry get file. This file (here filee) is a variable called type, this is the mime type of file.
function clickEvent() {
navigator.camera.getPicture(cameraSuccess, cameraError, {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM
});
}
function cameraSuccess(file_URI) {
window.resolveLocalFileSystemURI(file_URI, function(fileEntry) {
fileEntry.file(function(filee) {
alert(filee.type); //THIS IS MIME TYPE
}, function() {
alert('error');
});
}, onError);
}
function onError() {
alert('fehler resolve file system');
}
function cameraError() {
alert('fehler');
}

phonegap android cannot read image file

I am developing hybrid using phonegap 3.3. I am using camera plugin to capture image and store into photo album which working fine. Later, I have to read image file from the device storage.
I am using the following code.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, failFS);
function gotFS(fileSystem){
fileSystem.root.getFile(imageData, {create: true}, gotFileEntry, fail);
}
function gotFileEntry(){
fileEntry.file(gotFile,fail);
}
function gotFile(file){
alert(file.getParent().fullPath);
}
I am getting error in the first line. It is giving
FileError.ENCODING_ERR
I am not sure what I am doing wrong here. After, I have to move to another directory with new name. Could anyone help me to fix.
I am using camera plugin for capture images and file plugin to read files and directory.
--Sridhar
You can try with below code to capture and copy image
var pictureSource;
var destinationType;
var FileFolder = "";
var FileName = "";
var obj_imageCapture = {
capturePicture:function(imgFolder,imgName)
{
var image = imgFolder + imgName;
FileFolder = imgFolder;
FileName = imgName;
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
navigator.camera.getPicture(obj_imageCapture.onPhotoDataSuccess1, obj_imageCapture.onFail, {quality: 50, destinationType: destinationType.FILE_URI , saveToPhotoAlbum: true });
},
onPhotoDataSuccess1:function(imageData){
obj_imageCapture.createFileEntry(imageData);
},
createFileEntry:function(imageURI) {
window.resolveLocalFileSystemURI(imageURI, obj_imageCapture.copyPhoto, obj_imageCapture.onFFail);
},
copyPhoto:function(fileEntry) {
try
{
var ext = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('.'));
var imageN = "";
if(FileName.indexOf('.') > 0)
{
imageN = FileName.substr(0,FileName.lastIndexOf('.')) + ext;
}
else
{
imageN = FileName + ext;
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory(FileFolder, {create: true, exclusive: false}, function(dir) {
fileEntry.copyTo(dir, imageN, obj_imageCapture.onCopySuccess, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}
catch(ex)
{
alert(ex.message);
}
},
onCopySuccess:function(entry) {
var smallimage = document.getElementById("myimage");
smallimage.style.display = "block";
smallimage.src = entry.fullPath + "?rand=" + Math.random();
},
onFFail:function(message)
{
alert("Error in photo : " + message.message);
}
};
Above code might helpful to you

Nested directory creator: Phonegap

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

Categories

Resources