How to save image path in sqlite cordova - javascript

I want show the image taken from camera or chosen from gallery , after saving the image in filesystem then pushing the file image url into sqlite database successfully , I can't find a way to display it ,I tried the code below , it only insert the img path so far
var db = null;
angular.module('starter', ['ionic', 'ngCordova']) 
.run(function($ionicPlatform, $cordovaSQLite) {    
$ionicPlatform.ready(function() {      
try {        
db = $cordovaSQLite.openDB({          
name: "my.db",
          location: 'default'        
});        
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS imageTable " + "(id integer primary key, image text)");      
} catch (e) {        
alert(e);      
} finally {       }
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('ImageCtrl', function($scope, $rootScope, $state, $stateParams, $cordovaDevice, $cordovaFile, $ionicActionSheet, $cordovaCamera, $cordovaFile, $cordovaDevice, $ionicPopup, $cordovaActionSheet, $cordovaSQLite, $interval) {
var imagesP = [];
//$scope.images = [];
$scope.showAlert = function(title, msg) {
var alertPopup = $ionicPopup.alert({
title: title,
template: msg
});
};
$scope.loadImage = function() {
var options = {
title: 'Select Receipts Image ',
buttonLabels: ['Gallery', 'Take photo', 'File System'],
addCancelButtonWithLabel: 'Cancel',
androidEnableCancelButton: true,
};
$cordovaActionSheet.show(options).then(function(btnIndex) {
var type = null;
if (btnIndex === 1) {
type = Camera.PictureSourceType.PHOTOLIBRARY;
} else if (btnIndex === 2) {
type = Camera.PictureSourceType.CAMERA;
}
if (type !== null) {
$scope.selectPicture(type);
}
});
}
// Take image with the camera or from library and store it inside the app folder
// Image will not be saved to users Library.
$scope.selectPicture = function(sourceType) {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
correctOrientation: true,
targetWidth: 800,
targetHeight: 800,
popoverOptions: CameraPopoverOptions, // for IOS and IPAD
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
// alert(currentName);
//Create a new name for the photo to avoid duplication
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
//alert(newFileName);
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
var imgPath = cordova.file.dataDirectory + newFileName;
imagesP.push(imgPath);
$scope.add(imagesP);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
// alert( fileEntry.nativeURL);
};
});
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success) {
// $scope.image = newFileName;
//$scope.images.push(newFileName);
var image = cordova.file.dataDirectory + newFileName;
$scope.add(image);
}, function(error) {
$scope.showAlert('Error', error.exception);
});
}
},
function(err) {
// Not always an error, maybe cancel was pressed...
})
};
$scope.add = function(imagesP) {             
if (imagesP != null) {          
$cordovaSQLite.execute(db, "INSERT INTO imageTable (images) VALUES(?)", [imagesP] );        
}        
alert("Inserted.");      
},
function(e) {        
alert(e);      
};
$scope.delete = function(id) {                
if (id != '') {          
$cordovaSQLite.execute(db, DELETE FROM imageTable WHERE id=?", [id]);        
}        
alert("Deleted.");        
$scope.ShowAllData();      
},
function(e) {        
alert(e);      
};    
  
$scope.ShowAllData = function() { /* SELECT COMMAND */       
$scope.images = [];      
$cordovaSQLite.execute(db,"SELECT images FROM imageTable").then(function(res) {          
if (res.rows.length > 0) {            
for (var i = 0; i < res.rows.length; i++) {              
$scope.images.push({                
id: res.rows.item(i).id,
image: res.rows.item(i).images
              
});            
}          
}        
},         function(error) {          
alert(error);        
}      );
 
return $scope.images;    
} 
//$scope.ShowAllData();
 
//$interval($scope.ShowAllData, 2000,1);
       
// Returns the local path inside the app for an image
$scope.pathForImage = function() {
return cordova.file.dataDirectory + $scope.ShowAllData();
};
});
HTML
<body ng-app="starter" ng-controller="ImageCtrl">
<ion-pane>
<ion-header-bar class="bar-positive">
<h1 class="title"> Image Upload</h1>
</ion-header-bar>
<ion-content ng-repeat="image in images">
<img ng-src="{{image.image}}" style="width: 100%; height: 100%;">
</ion-content>
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-camera" ng-click="loadImage()">Take Photo</button>
<button class="button icon-left ion-camera" ng-click="ShowAllData()">show Photo</button>
</div>
</ion-footer-bar>
</ion-pane>
</body>

you can preview your image by setting destinationType to Camera.DestinationType.DATA_URL
var options = {
quality: 75,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: sourceType,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
correctOrientation: true,
targetWidth: 800,
targetHeight: 800,
popoverOptions: CameraPopoverOptions, // for IOS and IPAD
saveToPhotoAlbum: false
};
and in callback, use
"data:image/jpeg;base64," +imageData;
like this
$cordovaCamera.getPicture(options).then(function(imagePath) {
var currentImage = "data:image/jpeg;base64," +imagePath;
});

Related

In Safari, the canvas.toBlob function converts the image to png instead of webp

In Safari, the canvas.toBlob function converts the image to png instead of webp.
var myDropzone = new Dropzone("div#myDropzone", {
url: thisForm.getAttribute('action'),
paramName: function() { return 'mainFileUploader'; },
autoProcessQueue: false,
//createImageThumbnails: true, // this needs testing
//thumbnailWidth: 120, // this needs testing
//thumbnailHeight: 120, // this needs testing
//thumbnailMethod: "crop", // how to scale down the thumbnail if image not square
uploadMultiple: true,
parallelUploads: 4,
maxFiles: 4,
maxFilesize: 40000000, // MB
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
var myDropzone = this;
//Populate any existing thumbnails
if (photos) {
let photosNumber = photos.length
for (var i = 0; i < photosNumber; i++) {
var mockFile = {
name: photos[i],
size: 1000000,
type: 'image/webp',
status: Dropzone.ADDED,
accepted: true,
url: photos[i]
}
myDropzone.emit('addedfile', mockFile) // Call the default addedfile event handler
myDropzone.emit('thumbnail', mockFile, `/profiles/${goDatingCookie.userId}/photos/${photos[i]}`) // Show the thumbnail of the file
myDropzone.files.push(mockFile)
}
}
this.on("removedfile", function (file) {
if (file.url && file.url.trim().length > 0) { // Only files that have been programmatically added should have a url property.
let deletedPhotos = document.getElementById('deletedPhotos')
const fileName = file.url.replace(`/profiles/${goDatingCookie.userId}/photos/`, '')
if (deletedPhotos.value.length > 0) {
deletedPhotos.value = deletedPhotos.value + ',' + fileName
} else {
deletedPhotos.value = fileName
}
}
})
// for Dropzone to process the queue (instead of default form behavior):
const thisForm = document.forms['profileForm']
thisForm.addEventListener('submit', async function(e) {
e.preventDefault()
e.stopPropagation()
if (myDropzone.getQueuedFiles().length == 0) {
if (goDatingCookie.hasProfile) {
thisForm.append("lookingForReligions", getMultiSelect("lookingForReligions"))
thisForm.append("lookingForCountries", getMultiSelect("lookingForCountries"))
let formData = new FormData(thisForm)
const response = await getAndPostData({
url: thisForm.getAttribute('action'),
method: thisForm.getAttribute('method'),
enctype: thisForm.getAttribute('enctype'),
data: formData
})
if (response == HTTP204NoContent) {
location.hash = "#viewMyProfile"
}
} else {
new SystemMessage("You require a photo to create a profile.")
}
} else {
myDropzone.processQueue()
}
});
//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append('nickname', thisForm.elements.nickname.value)
formData.append('dateOfBirth', thisForm.elements.dateOfBirth.value)
formData.append('description', thisForm.elements.description.value)
formData.append('gender', thisForm.elements.gender.value)
formData.append('sexuality', thisForm.elements.sexuality.value)
formData.append('alcohol', thisForm.elements.alcohol.value)
formData.append('smoke', thisForm.elements.smoke.value)
formData.append('religion', thisForm.elements.religion.value)
formData.append('country', thisForm.elements.country.value)
formData.append('location', thisForm.elements.location.value)
formData.append('interests', thisForm.elements.interests.value)
formData.append('lookingForFromAge', thisForm.elements.lookingForFromAge.value)
formData.append('lookingForToAge', thisForm.elements.lookingForToAge.value)
formData.append('deletedPhotos', thisForm.elements.deletedPhotos.value)
formData.append("lookingForReligions", getMultiSelect("lookingForReligions"))
formData.append("lookingForCountries", getMultiSelect("lookingForCountries"))
});
this.on("successmultiple", function(files, response) {
goDatingCookie = JSON.parse(getCookie('goDatingCookie'))
location.hash = '#viewMyProfile'
});
this.on("errormultiple", function(files, response) {
new SystemMessage("There were problems uploading your profile.")
})
},
transformFile: function(file, done) {
// Create Dropzone reference for use in confirm button click handler
var myDropzone = this
// Create the image editor overlay
var editor = document.createElement('div');
editor.style.position = 'fixed';
editor.style.left = 0;
editor.style.right = 0;
editor.style.top = 0;
editor.style.bottom = 0;
editor.style.zIndex = 9999;
editor.style.backgroundColor = '#000';
document.body.appendChild(editor);
// Create confirm button at the top left of the viewport
var buttonConfirm = document.createElement('button');
buttonConfirm.style.position = 'absolute';
buttonConfirm.style.left = '50%';
buttonConfirm.style.top = '10px';
buttonConfirm.style.zIndex = 9999;
buttonConfirm.classList = "btn btn-godating btn-lg mt-4 rounded-pill"
buttonConfirm.textContent = 'Confirm';
editor.appendChild(buttonConfirm);
buttonConfirm.addEventListener('click', function() {
// Get the canvas with image data from Cropper.js
var canvas = cropper.getCroppedCanvas({
width: 1200,
height: 1200,
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high'
});
// Turn the canvas into a Blob (file object without a name)
canvas.toBlob(function(blob) {
// Create a new Dropzone file thumbnail
myDropzone.createThumbnail(
blob,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod,
false,
function(dataURL) {
// Update the Dropzone file thumbnail
myDropzone.emit('thumbnail', file, dataURL);
// Return the file to Dropzone
done(blob);
});
}, 'image/webp', 0.80);
// Remove the editor from the view
document.body.removeChild(editor)
});
// Create an image node for Cropper.js
var image = new Image();
image.src = URL.createObjectURL(file);
editor.appendChild(image);
// Create Cropper.js
var cropper = new Cropper(image, { viewMode: 1, autoCropArea: 1, aspectRatio: 1 });
}
});
On the receiving server it reports the following about the file:
fileFilter {
fieldname: 'mainFileUploader',
originalname: 'Me - Profile.jpg',
encoding: '7bit',
mimetype: 'image/png'
}
This is the same for Safari on the Apple Mac or iPhone.
On Chrome or Firefox on my Apple Mac it works perfectly and the receiving server reports:
fileFilter {
fieldname: 'mainFileUploader',
originalname: 'Me - Profile.jpg',
encoding: '7bit',
mimetype: 'image/webp'
}
Is there anyway of getting Safari to behave or do I just need to use jpeg files or convert the incorrectly converted png on the server side to webp?

Displaying image taken from camera

As you can see below, I am using the [src] attribute. What I am trying to do is preview the image taken from a device's camera. Please see the rest of the typescript code below.
<img [src]="lastImage" style="width: 100%" [hidden]="lastImage === null">
<button ion-button icon-left (click)="presentActionSheet()">
<ion-icon name="camera"></ion-icon>Select Image
</button>
Here is .ts code
lastImage: string = null;
public presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
title: 'Select Image Source',
buttons: [
{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
public takePicture(sourceType) {
// Create options for the Camera Dialog
var options = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
// Get the data of an image
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
if (this.platform.is('ios') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
alert('IF');
this.filePath.resolveNativePath(imagePath).then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
// alert(correctPath);
alert(correctPath + currentName);
this.lastImage = correctPath + currentName;
// this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
} else {
alert('ELSE'); // This part runs
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
alert(cordova.file.dataDirectory + currentName); // This returns proper image path
this.lastImage = cordova.file.dataDirectory + currentName;
alert(this.lastImage); // this also has the image path.
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}, (err) => {
this.presentToast('Error while selecting image.');
});
}
Now when I choose image Use Camera then it opens the camera and I take a photo. But somehow the photo is not previewed in my above HTML where I am using [src]="lastImage". What is wrong with my code that it does not show any image from the camera?
UPDATE
I also used normalizeURL which I found here like following!
import { normalizeURL } from 'ionic-angular';
this.lastImage = normalizeURL(cordova.file.dataDirectory + currentName);
What happens with this piece of code is that it replaces file:/// part with http://localhost:8080 whereas I am taking a photo from the camera which local not any server and want to display that on img tag.
He, I suggest that use base64 to set image to img tag, check the next code:
Controller atribute
private base64Image: any = false;
In your controller constructor set: "public domSanitizer: DomSanitizer" as parameter, this allow say to angular that the image is "safe".
Controller method
takePicture() {
const options: CameraOptions = {
quality: 10,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
this.message("Error, your camera device not work");
});
}
In your view file
<img *ngIf="base64Image != 'false'" [src]="domSanitizer.bypassSecurityTrustUrl(base64Image)">
import { normalizeURL } from 'ionic-angular';
<img *ngIf="base64Image" src="{{base64Image}}"/>
openCamera(pictureSourceType: any) {
let options: CameraOptions = {
quality: 95,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: pictureSourceType,
encodingType: this.camera.EncodingType.PNG,
targetWidth: 400,
targetHeight: 400,
saveToPhotoAlbum: true,
correctOrientation: true
};
this.camera.getPicture(options).then(imageData => {
if (this.platform.is('ios'))
this.base64Image = normalizeURL(imageData);
// IF problem only occur in ios and normalizeURL
//not work for you then you can also use
//this.base64Image= imageData.replace(/^file:\/\//, '');
else
this.base64Image= "data:image/jpeg;base64," + imageData;
}, error => {
console.log('ERROR -> ' + JSON.stringify(error));
});
}
in my case, when i'm setting src to image tag in my localhost it is giving some unsafe security issue ERR_UNKNOWN_URL_SCHEME.
so i used DomSanitizer to bypassSecurity like below.
constructor(private senitizer: DomSanitizer) {}
this.imageUrl = <string>this.senitizer.bypassSecurityTrustUrl(this.imageUrl);
so check your console and if there is same problem, then instead of 'normalizeURL' use above code to bypass security for localhost.
or if you deploy your code on some secure domain (https), it does not require security bypass.
Probably it passes the LOCATION to the src (instead of URL). You can:
1) Move the picture file (i.e from C:/path/file.jpg ) into the LOCALHOST's www root folder and use url http://localhost/file.jpg in src attribute.
or
2) convert/append image to <canvas> element ( but learn some basics of that)
or
3) As advised already, convert image to BASE64 string (not nice way, but works) and append the data to src.
May this code helps you
App Component
export class AppComponent implements OnInit{
video: any;
canvas: any;
ngOnInit() {
this.startup();
}
startup(): void {
this.video = document.getElementById('video');
this.canvas = document.getElementById('canvas');
const nav = <any>navigator;
nav.getUserMedia = nav.getUserMedia || nav.mozGetUserMedia || nav.webkitGetUserMedia;
const self = this;
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function (stream) {
self.video.srcObject = stream;
self.video.play();
});
}
onBtnClicked(event: Event): void {
this.takePicture();
event.preventDefault();
}
takePicture() {
const context = this.canvas.getContext('2d');
context.drawImage(this.video, 0, 0, 100, 100);
}
}
And component's template is :
<div class="camera">
<video id="video" #video
width="width"
height="height"
(canplay)="onCanPlay($event)">
Video stream not available.
</video>
</div>
<canvas id="canvas" #canvas
width="width"
height="height">
</canvas>
<button (click)="takePicture()">Take Picture</button>
For detail check this
view template:
<img style="margin:5px; width: 100%" *ngIf="imageURL" src={{this.imageURL}} #myImage (click)="presentImage(myImage)" imageViewer/>
<button ion-button icon-left (click)="presentActionSheet()">
<ion-icon name="camera"></ion-icon>Select Image
</button>
TypeScript:
import { Camera,CameraOptions, CameraPopoverOptions } from '#ionic-native/camera';
import { ImageViewerController } from 'ionic-img-viewer';
then add 'Camera' in providers:
#Component({
//.....
providers: [Camera],
//....
})
then initialize the given objects:
_imageViewerCtrl: ImageViewerController;
imageURL;
camera: Camera;
then
options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
public presentActionSheet(){
this.camera.getPicture(this.options).then((imageData) => {
this.imageURL = 'data:image/jpeg;base64,' + imageData;
this.presentImage(this.imageURL);
}, (err) => {
console.log(err);
});
}
presentImage(myImage) {
const imageViewer = this._imageViewerCtrl.create(myImage);
imageViewer.present();
}

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.

angularjs ng-resource Asynchronously Upload

I am uploading about 10 photos at a time (photos ranging unto 800kb - 1000kb per photo).
My issue is, that the app crashes after about 5 seconds.
How do I upload the photos Asynchronously and maybe improve the performance of the app?
Controller
appcon.controller('myCtrl', function($scope, $state, $cordovaCamera, $ionicPopup, PostImg){
$scope.postData = [];
var truckid = "%" + window.localStorage['truckid'] + "%";
$scope.start = function() {
document.addEventListener("deviceready", function () {
var options = {
quality: 200,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 1000,
targetHeight: 1000,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
$cordovaCamera.getPicture(options).then(function(imageData) {
var file = imageData;
$scope.postData.push({file});
}, function(err) {
console.log('4 error');
});
}, false);
}
$scope.upload = function() {
var confirmPopup = $ionicPopup.confirm({
title: 'Continue?',
template: 'Are you sure you want to Send Images?'
});
confirmPopup.then(function(res) {
if(res) {
$scope.postData.push({truckid});
var post = new PostImg($scope.postData);
post.$save(function(postObject) {
var alertPopup = $ionicPopup.alert({
title: 'Images Send !',
buttons: [{
text: 'Continue with Check In?',
type: 'button-positive'
}]
});
alertPopup.then(function(res) {
});
});
}
else {
console.log('You are not sure');
}
});
}
})
Factory
appcon.factory('PostImg', function($resource) {
return $resource('http://192.168.0.1/Service.svc/BOB');
});
Can you try cordova-plugin-file-transfer. Please note that it will work only in phone.
http://ngcordova.com/docs/plugins/fileTransfer/

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.

Categories