angularjs ng-resource Asynchronously Upload - javascript

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/

Related

How to manipulate image (crop and resizing) after take photo or select photo from library using ionic 5

basically, I need to manipulate the picture that I select before viewing it in it's place in HTML page.
what I did so far is action sheet that have two options Load image or pick image :
async selectImage() {
const actionSheet = await this.actionSheetController.create({
header: 'Select Image source',
buttons: [{
text: 'Load from Library',
handler: () => {
this.pickImage(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.pickImage(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
}
and this is pickImage function
pickImage(sourceType) {
const options: CameraOptions = {
quality: 100,
sourceType,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation: true,
};
this.camera.getPicture(options)
.then((imageData) => {
this.crop.crop(imageData, {quality: 100 });
this.serviceps.logo = 'data:image/jpeg;base64,' + imageData;
}, error => console.error('Error cropping image', error));
}
so now how can I add the cropping and editing image just right after choosing it ? I've been trying since yesterday but I couldn't do it.

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.

How to save image path in sqlite cordova

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;
});

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.

Cordova choose video resulting path without extension

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,
});
}

Categories