Cordova choose video resulting path without extension - javascript

I am using below code to select a video from library
navigator.camera.getPicture(function (data) {
callback(true, data);
},
function (e) {
callback(false, null);
}, {
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
mediaType: navigator.camera.MediaType.VIDEO
});
But in callback I am getting path in below format
content://media/external/video/media/832
How can I get the original file path?

I know its to late but maybe someone else needs this ( use resolveLocalFileSystemURL then toURL() )
check this code
navigator.camera.getPicture(onSuccess, onFail, {
limit: 1,
mediaType: window.Camera.MediaType.VIDEO,
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
});
function onSuccess(fileURI) {
window.resolveLocalFileSystemURL(fileURI,
function (fileEntry) {
console.log(fileEntry.toURL());
//console.log(fileEntry.fullPath);
},
function () { });
}
function onFail(error) {
console.log(error);
}

step1
cordova plugin add cordova-filepath-resolver
For Ionic specifically, you can also use:
ionic plugin add cordova-filepath-resolver
step2
put this code
function camerasucess(videourl) {
//videourl is something like this content //media/external/video
var successCallback = function (data) {
console.log(JSON.stringify(data));
//here you will get the correct path of the video file and you can upload the video file
$scope.data = data;
};
var errorCallback = function (data) {
console.log(JSON.stringify(data));
};
window.FilePath.resolveNativePath(videourl, successCallback, errorCallback);
};
function cameraError(data) {
alert(JSON.stringify(data));
};
if (navigator.camera)
{
navigator.camera.getPicture(camerasucess, cameraError, {
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, mediaType: navigator.camera.MediaType.VIDEO,
});
}

Related

Download progress bar pops and ends up, with no errors and no output file in the device

I am creating a image download server for my APP with Rest API, there are two buttons in the HTML, one is download button and other is load button.
When clicked on download button progress bar shows the progress, but there is no output file and doesn't show any error even load button doesn't load anything.
This script works fine with static URL (without API) by making certain changes in the script.
Link for my temporary Server.
http://freaksearch.com/aarti/rest-api.php?json=image&Id=
Plugin required by this script : cordova-plugin-file-transfer
(this is not depreciated plugin)
Link for the plugin: https://www.npmjs.com/package/cordova-plugin-file-transfer
Here is my HTML:
<div class="padding">
<button class="button" ng-click="download()">Download</button>
<button class="button" ng-click="load()">Load</button>
{{imgFile}}
<img ng-src="{{imgFile}}">
</div>
Here is my script:
$scope.download = function(imageId, imageName) {
$ionicLoading.show({
template: 'Downloading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getDirectory(
"MyProject",
{
create: true
},
function (dirEntry) {
dirEntry.getFile(
imageName + ".jpg",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI('http://freaksearch.com/aarti/rest-api?json=image' + imageId),
p,
function (entry) {
$ionicLoading.hide();
$scope.imgFile = 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");
});
}
$scope.load = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
"MyProject",
{
create: false
},
function(dirEntry) {
dirEntry.getFile(
imageName + ".jpg",
{
create: false,
exclusive: false
},
function gotFileEntry(fe) {
$ionicLoading.hide();
$scope.imgFile = fe.toURL();
},
function(error) {
$ionicLoading.hide();
console.log("Error getting file");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Error requesting filesystem");
});
}
Adding <preference name="AndroidPersistentFileLocation" value="Compatibility" />to the config.xml made my folder & file visible. I hope this could help someone.
Now i can see the images, but all the images are Corrupt.

Javascript cordova camera picture not uploading to firebase

I am trying to upload camera picture from cordova app to firebase storage. It is working fine in webbrowser but not working through cordova. I have searched a lot but not able to find the exact solution.
This is the code i have written:-
onOpenCamera: function(oEvent){
var oImage = this.getView().byId("profilePicId");
navigator.camera.getPicture(onSuccess, onFail, {
quality: 25,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA
});
function onSuccess(imageURI) {
//var options = { quality: 100 };
//plugins.crop(function success (newPath) {
oImage.setSrc(imageURI);
var sBusyDialog = new BusyDialog({
customIcon: "Images/loader.gif",
customIconDensityAware: false
});
sBusyDialog.open();
var profileUploadRequest = Firebase.uploadFile('users/'+ Firebase.currentUser().uid + '/Profile.png', imageURI);
profileUploadRequest.then(function(snapshot){
sBusyDialog.close();
var oProfileUpdate = Firebase.updateProfilePic(snapshot.downloadURL);
oProfileUpdate.catch(function(oError){
sBusyDialog.close();
var message = oError.message;
MessageBox.show(message, {
title : oError.code,
icon : sap.m.MessageBox.Icon.ERROR
});
});
});
profileUploadRequest.catch(function(oError){
sBusyDialog.close();
var message = oError.message;
MessageBox.show(message, {
title : oError.code,
icon : sap.m.MessageBox.Icon.ERROR
});
});
/* }, function fail (error) {
MessageToast.show('Failed because: ' + error);
}, imageURI, options);*/
}
function onFail(message) {
MessageToast.show('Failed because: ' + message);
}
},
This is Firebase file:-
uploadFile: function(path, dataUrl){
var storageRef = firebase.storage().ref();
var profileRef = storageRef.child(path);
return profileRef.putString(dataUrl, 'data_url');
},
Please check it once.
I have went through all the stackoverflow solutions like creating a blob, using cordova file plugin. I have read in firebase that cordova doesn't support file upload but download works.
Thanks.

Unable to get cordovaCapture to work using ngCordova on ionic

I am unable to get cordovaCapture.captureVideo to work. Using cordovaCamera lets me use the camera to take photos and choose photos from the library without any problems but I am trying to to use cordovaCapture to use take a video on iOS, I would also like to get a thumbnail or image preview of the video to show on the view once the video is taken.
I have included the code below which uses both cordovaCamera and cordovaCapture. I have followed the examples on ngCordova website.
.controller("CameraController", function($scope, $cordovaCamera, $cordovaCapture) {
$scope.takePhoto = function () {
var options = {
quality: 75,
cameraDirection: Camera.Direction.FRONT,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
}, function (err) {
// An error occured. Show a message to the user
});
}
$scope.choosePhoto = function () {
var options = {
quality: 75,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
}, function (err) {
// An error occured. Show a message to the user
});
}
$scope.captureVideo = function() {
var options = { limit: 1, duration: 15 };
$cordovaCapture.captureVideo(options).then(function(videoData) {
// Video data
}, function(err) {
// An error occurred. Show a message to the user
});
}
})
I see that you use $cordovaCamera and $cordovaCapture inside controller.
This means that you need to install both
$ cordova plugin add cordova-plugin-camera from $cordovaCamera
and
$ cordova plugin add cordova-plugin-media-capture from $cordovaCapture
If takePhoto() works, but captureVideo() does not, this means that you did not install $cordovaCapture.

Opening a PDF in cordova javascript

I have generated a PDF invoice using the file plugin. Now I want to open the file in the app. I tried inAppBrowser, but its giving an empty page. I tried fileopener, its neither giving a success or failed message. How do I specify the path to my file . please help!!
In app Browser Method
var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
cdr=dir;
alert("cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log(" write success");
};
console.log("writing to file");
writer.write( pdfOutput );
},function () {
console.log("ERROR SAVEFILE");
});
});
});
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
alert("open file");
dir.getFile("test.pdf", {create:false}, function(fileEntry) { //EXISTS
alert("native url "+cdr.toNativeURL());
var url =cdr.toNativeURL() + "test.pdf";
alert(url);
window.open(url, '_blank');
}, function() { //NOT EXISTS
alert("no file found");
});
});
}
Fileopener Method
var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory , function(dir) {
cdr=dir;
console.log(" vidhya cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log("vidhya write success");
openFile(cdr);
};
console.log("vidhya writing to file");
writer.write( pdfOutput );
},function () {
console.log("vidhya ERROR SAVEFILE");
});
});
});
function openFile(cdr) {
var fs;
function fsSuccess(fileSystem)
{
fs = fileSystem;
console.log("vidhya "+fs);
}
function fsFail(event)
{
console.log(event.target.error.code);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsFail);
console.log("vidhya opening file " +cdr.toNativeURL());
cordova.plugins.fileOpener2.open(
fs.root.toURL() +'test.pdf',
"application/pdf", //mimetype
{
error: function(e) {
alert("Error Opening the File.Unsupported document format.");
},
success: function() {
// success callback handler
alert("success");
}
}
);
}
My file is getting saved in /internal storage/Android/Data/app_folder/files/test.pdf
This is how i made it work in my hybrid mobile app:
var cdr;
sessionStorage.platform = device.platform;
var fileTransfer = new FileTransfer();
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
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) {
dir.getDirectory("My_App", {
create: true,
exclusive: false
}, onGetDirectorySuccess1, onGetDirectoryFail);
};
function onGetDirectorySuccess1(dir) {
cdr = dir;
dir.getFile(filename, {
create: true,
exclusive: false
}, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
var documentUrl = "http://myserverurl.com/test.pdf";
var uri = documentUrl;
fileTransfer.download(uri, cdr.nativeURL + docFileNameToView,
function(entry) {
openFile();
},
function(error) {
navigator.notification.alert("Error");
},
false
);
};
function openFile() {
cordova.plugins.fileOpener2.open(
cdr.nativeURL + docFileNameToView,
'application/pdf', {
error: function(e) {
navigator.notification.alert("Error Opening the File.Unsupported document format.");
},
success: function() {
}
}
);
};
function fail(error) {
navigator.notification.alert("Error");
};
function errorHandler(e) {
navigator.notification.alert("Error");
};
function onGetDirectoryFail(error) {
navigator.notification.alert("Error");
};
This code uses cordova file transfer plugin to download pdf and file opener plugin to view the pdf. This sample code also use device plugin to get the device platform (iOS or Android) and dialog plugin to display notification.
Code was tested on iOS 9 and Android 6 devices and works fine. In Android, the file gets stored in storage/emulated/0/Cordova/My_App folder
If someone faces an issue while opening the file stored in device even with proper destination file path specified, please do ensure that the file is downloaded properly without corruption.
Many a times file opening fails due to improper or corrupted download. You can also trace any error during download using chrome inspect devices option. Also ensure to use latest version of file transfer plugin to avoid download error.

filter files in Blueimp/ jQuery-File-Upload

I am trying to use Blueimp / jQuery-File-Upload my project and I want to test the file extension because I only want to download photos
someone show me where and how I should configure blueimp / jQuery-File-Upload so I can do this
As stated in the documentation you can simply set the options to a regex for the file type like that:
$('#fileupload').fileupload('option', {
url: '//localhost/',
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
process: [
{
action: 'load',
fileTypes: /^image\/(gif|jpeg|png)$/,
maxFileSize: 20000000 // 20MB
},
{
action: 'resize',
maxWidth: 1440,
maxHeight: 900
},
{
action: 'save'
}
]
});
I found this add method
So, here is my code for .gpx files:
$('#fileupload').fileupload({
// your fileupload options
add:function(e,data){
data.files.map(function(i){
if(i.type!='application/gpx+xml'){
alert('please upload only .gpx files');
}else{
data.submit();
}
}),
process: function(e,data){/* your process actions here */}
});
Your can use the method add for filter files:
var $input = $('#upload_input');
$input.fileupload({
fileInput: $input,
url: 'YOU_URL',
// Other options...
start: function(e, data) {
// Before start upload... Please wait...
},
add: function(e, data) {
types = /(\.|\/)(gif|jpe?g|png)$/i;
file = data.files[0]
if (types.test(file.type) || types.test(file.name)) {
data.submit();
} else {
// alert('Unfortunately, we don’t support that file type. Try again with a PNG, GIF, JPG');
return;
}
},
done: function(e, data) {
// After upload... alert('Done');
},
fail: function(e, data) {
// Error. Please try again later...
}
});

Categories