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
Related
I need to upload all type of files in my application and for images I need to get image height and width and for that I am using:
$scope.uploadFile = function(){
$scope.imageUploading = true;
var options = {
quality: 70,
//~ targetWidth: 1005,
//~ targetHeight: 693,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: Camera.MediaType.PICTURE,
correctOrientation: true
};
$cordovaCamera.getPicture(options).then(function(imageData) {
imageData = imageData.split('?');
var imageURI = imageData[0];
// This function is called once an imageURI is rerturned from PhoneGap's camera or gallery function
window.resolveLocalFileSystemURL(imageURI, function(fileEntry) {
fileEntry.file(function(fileObject){
// Create a reader to read the file
var reader = new FileReader();
// Create a function to process the file once it's read
reader.onloadend = function(evt) {
// Create an image element that we will load the data into
var image = new Image()
image.onload = function(evt) {
// The image has been loaded and the data is ready
var image_width = this.width
var image_height = this.height
if(parseInt(image_width) < confArr.image_sizes.portfolio.large.w || parseInt(image_height) < confArr.image_sizes.portfolio.large.h){
Auth.toastMessage($rootScope.appMainLang.formvalidation.upload_resolution_limit.replace('%s',parseInt(confArr.image_sizes.portfolio.large.w)),'long','center');
$scope.imageUploading = false;
$ionicLoading.hide();
}else{
$scope.imageUploading = true;
$scope.jrCrop(imageURI);
}
image = null
}
// Load the read data into the image source. It's base64 data
image.src = evt.target.result
}
// Read from disk the data as base64
reader.readAsDataURL(fileObject)
}, function(){
Auth.toastMessage("There was an error reading or processing this file.","long", "center");
})
})
}, function(err) {
$scope.imageUploading = false;
$ionicLoading.hide();
// Auth.toastMessage(Auth.getlocal("timeoutText","string"),"long", "center");
});
}
when I use
mediaType: Camera.MediaType.PICTURE,
in above code it returns path of file as "file:///storage/emulated/0/...." and is working correctly.
but as I need to upload all types of files so I replaced above line with
mediaType: Camera.MediaType.ALLMEDIA
and with this path of file becomes "/storage/emulated/0/..." and then it do not enters in "window.resolveLocalFileSystemURL" function.
So is there a way to convert this later path to above mentioned like path?
Just add the file:// to the string. Like this:
var imageURI = 'file://' + imageData[0];
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.
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);
}
I have downloaded a PDF file as Base64 String in my phone as described in this SO Thread but I am not getting how can I render it to actual PDF so that end user can see it? I have written following code to write on the file:
var tempResponse = null;
function downloadFileOK(response){
var invocationResult = response['invocationResult'];
tempResponse = invocationResult;
var size = parseInt(invocationResult["responseHeaders"]["Content-Length"]);
window.requestFileSystem(LocalFileSystem.PERSISTENT, size, onSuccessFileHandler, onErrorFileHandler);
}
//Success
function onSuccessFileHandler(fileSystem) {
alert("inside onSuccessFileHandler START");
fileSystem.root.getFile("test2.pdf", {create: true, exclusive: false}, fileWriter, fail);
alert("inside onSuccessHandler END");
}
// Failure
function onErrorFileHandler(error) {
alert("inside onErrorFileHandler");
}
function fileWriter(entry){
alert("inside fileWriter START");
entry.createWriter(function(writer){
writer.onwriteend = function(evt) {
console.log("done written pdf :: test1.pdf");
alert("Inside onwriteend : START");
};
var temp = atob(tempResponse["text"]);
alert(temp);
writer.write(temp);
},fail);
alert("inside fileWriter END");
}
function fail(error) {
alert("inside fail");
console.log(error.code);
}
Am I doing it wrong? How can I open the PDF from my app in iOS/Android OS using javascript/jquery/cordova ?
Once you have download the base64 encoded file, you should decode it and save it to the file system so that it can be viewed later. You should not save the base in it's base64 encoded form.
You can use the utility function below to accomplish that. BTW you should take a look a the previous answer on Download PDF file from through MobileFirst Adapter since I made an update to it, it wasn't encoding the PDF properly.
var AppUtils = (function(){
// get the application directory. in this case only checking for Android and iOS
function localFilePath(filename) {
if(device.platform.toLowerCase() === 'android') {
return cordova.file.externalDataDirectory + filename;
} else if(device.platform.toLowerCase() == 'ios') {
return cordova.file.dataDirectory + filename;
}
}
// FileWritter class
function FileWritter(filename) {
this.fileName = filename;
this.filePath = localFilePath(filename);
}
// decode base64 encoded data and save it to file
FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
var byteData = atob(data);
var byteArray = new Array(byteData.length);
for (var i = 0; i < byteData.length; i++) {
byteArray[i] = byteData.charCodeAt(i);
}
var binaryData = (new Uint8Array(byteArray)).buffer;
this.saveFile(binaryData, ok, fail);
}
// save file to storage using cordova
FileWritter.prototype.saveFile = function(data, ok, fail) {
this.fileData = data;
var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));
var that = this;
// Write file on local system
window.resolveLocalFileSystemURL(path, function(directoryEntry) {
var options = {create: true, exclusive: false};
directoryEntry.getFile(that.fileName, options, function(file) {
file.createWriter(function(writer) {
writer.onwriteend = function(event) {
if(typeof ok === 'function') {
ok(event);
}
};
writer.write(that.fileData);
}, fail);
}, fail);
}, fail);
};
// open InApp Browser to view file
function viewFile(filename) {
var path = localFilePath(filename);
window.open(path, "_blank", "location=yes,hidden=no,closebuttoncaption=Close");
}
return {
FileWritter: FileWritter,
localFilePath: localFilePath,
viewFile: viewFile
}
})();
Your downloadFileOK should look as follow:
function downloadFileOK(response){
var pdfData = response['invocationResult']['text'];
var fileWritter = new AppUtils.FileWritter('YOUR-PDF-NAME.pdf');
fileWritter.saveBase64ToBinary(pdfData, function(r){
// file was saved
}, function(e){
// error file was not saved
});
}
If you want to open the file then you can use AppUtils.viewFile('YOUR-FILE-NAME.pdf')
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");
});
}