ngcordova android file select and upload to server - android

I want to upload file from my ionic application to server. I am using cordovafiletransfer plugin. Using that I am able to upload file by providing static path in controller code. My question is how to get selected file path by user? I only get filename from input tag on the relative path of selected file. How to get that?
View Page Code:
<label class="item item-input">
<div class="input-label">Upload Photo</div>
<input type="file" onchange="angular.element(this).scope().setFile(this)" accept="image/*"/>
</label>
<div class="padding">
<button ng-click="upload()" class="button button-block button-assertive">Upload</button>
</div>
Controller Code:
$scope.upload = function() {
var filename, options, targetPath;
console.log($scope.theFile);
targetPath = cordova.file.externalRootDirectory + '/Download/androidify.png';
filename = targetPath.split('/').pop();
options = {};
options.fileKey = 'image_file';
options.fileName = $scope.theFile.name;
options.chunkedMode = false;
options.mimeType = $scope.theFile.type;
options.headers = {
'Authorization': getDeviceToken()
};
console.log(options);
return $cordovaFileTransfer.upload(domain.uploadphoto(), targetPath, options).then(
(function(result) {
console.log('SUCCESS: ' + JSON.stringify(result.response));
}),
(function(err) {
console.log('ERROR: ' + JSON.stringify(err));
}),
function(progress) {}
);
};
$scope.setFile = function(element) {
return $scope.$apply(function($scope) {
console.log(element);
return $scope.theFile = element.files[0];
});
};
How to get proper target path of selected file?

I came across this post which should solve the problem, (it works for me, with some modification):
In my template:
<input type="file" fileread="file.path" />
<button type="button" class="button button-small button-assertive" ng-click="vm.upload(file)">Upload PDF</button>
and my modified Directive:
.directive("fileread", ['$cordovaFile', function ($cordovaFile) {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
var fileName = changeEvent.target.files[0].name;
$cordovaFile.writeFile(cordova.file.dataDirectory, fileName, loadEvent.target.result, true)
.then(function (result) {
console.log(result)
}, function (err) {
console.warn(err)
});
scope.$apply(function () {
scope.fileread = cordova.file.dataDirectory + fileName;
});
}
reader.readAsArrayBuffer(changeEvent.target.files[0]);
});
}
}
}]);
Remember to clean up after you uploaded the document
use:
$cordovaFile.removeFile(cordova.file.dataDirectory, fileName)
.then(function (success) {
// success
}, function (error) {
// error
});
Also see http://www.javascripture.com/FileReader for more info regarding FileReader

Related

How can I put a video in ionic with mediaCapture?

In the app I get this error Object: object,
After recording the video when giving it ready to be displayed on the screen I get that error.
VideoPage.HTML
<ion-header>
<ion-toolbar color="primary">
<ion-title>Subir Video</ion-title>
<ion-buttons slot="start">
<ion-back-button defaultHref="/autoventa"></ion-back-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-progress-bar [value]="uploadProgress" color="tertiary"></ion-progress-bar>
<ion-list>
<ion-item-sliding *ngFor="let f of files">
<ion-item (click)="openFile(f)">
<ion-icon name="videocam" slot="start" *ngIf=" f.name.endsWith('mp4')"></ion-icon>
<ion-label class = "ion-text-wrap">
{{ f.name }}
<p> {{ f.fullPath }}</p>
</ion-label>
</ion-item>
<ion-item-options side="start">
<ion-item-option (click)="deleteFile(f)" color="danger">
<ion-icon name="trash" slot="icon-only"></ion-icon>
</ion-item-option>
</ion-item-options>
<ion-item-options side ="end">
<ion-item-option (click)="uploadFile(f)" color = "primary">
<ion-icon name="cloud-upload" slot = "icon-only"></ion-icon>
</ion-item-option>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>
<ion-footer>
<ion-toolbar color = "primary">
<ion-button fill="clear" expand="full" color="light" (click)="selectMedia()">
<ion-icon slot = "start" name="document"></ion-icon>
Seleccionar Media
</ion-button>
</ion-toolbar>
</ion-footer>
Declaration of Variables
media folder... I put it before the #component
and files[] before the constructor
const MEDIA_FOLDER_NAME = 'my_media';
files = [];
my recordVideo in videoPage.ts
I use this method to open the camera and record, this part works but at the moment of giving it ready I get an Object object error
recordVideo(){
this.mediaCapture.captureVideo().then(
(data: MediaFile[]) => {
if(data.length > 0 ){
this.copyFileToLocalDir(data[0].fullPath)
}
},
(err: CaptureError) => {
console.log(err)
alert(err);
}
);
}
CopyFile
after recording command to call this method
but I think the error is in this method
copyFileToLocalDir(fullPath){
let myPath = fullPath;
// Make sure we copy from the right location
if (fullPath.indexOf('file://') < 0) {
myPath = 'file://' + fullPath;
}
const ext = myPath.split('.').pop();
const d = Date.now();
const newName = `${d}.${ext}`;
const name = myPath.substr(myPath.lastIndexOf('/') + 1);
const copyFrom = myPath.substr(0, myPath.lastIndexOf('/') + 1);
const copyTo = this.file.dataDirectory + MEDIA_FOLDER_NAME;
this.file.copyFile(copyFrom, name, copyTo, newName).then(
success => {
this.loadFiles();
},
error => {
console.log('error: ', error);
alert(error);
}
);
}
LoadFiles with this method I show the files
loadFiles(){
this.file.listDir(this.file.dataDirectory, MEDIA_FOLDER_NAME).then(
res => {
this.files = res;
},(err)=> {
console.log('Error al cargar archivos: ', err);
alert(err);
}
);
}
ngOnInit
ngOnInit() {
this.plt.ready().then(() =>{
let path = this.file.dataDirectory +MEDIA_FOLDER_NAME;
this.file.checkDir(path, MEDIA_FOLDER_NAME).then(
() => {
this.loadFiles();
},
err => {
this.file.createDir(path, MEDIA_FOLDER_NAME, false);
}
);
});
}

Display image from internal storage in Vue + Cordova

I am trying to display an image from download folder.
imagePath: file:///storage/emulated/0/Download/sample.png
Set Image URL:
window.resolveLocalFileSystemURL(this.imagePath, function success(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
if (this.result) {
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
this.imgUrl = window.URL.createObjectURL(blob);
}
};
reader.readAsArrayBuffer(file);
});
}, function (err) {
this.info = 'An error was found: '+ err;
});
Display it on UI:
<img class="img-fluid" src="{{imgUrl}}" />
But code is not reaching inside onloadend callback.

File download in angular js

How to download a file in a mobile device while giving the URL from the server, In Angularjs mobile application(Platform Cordova). The file can be of type pdf, image etc...
You have to do something like this:
This is Angular JS part:
import { Http, ResponseContentType } from '#angular/http';
...
constructor(
private http: Http,
) { }
downloadFile() {
return this.http
.get('http://www.africau.edu/images/default', {
responseType: ResponseContentType.Blob,
search: // query string if have
})
.map(res => {
return {
filename: 'sample.pdf',
data: res.blob()
};
})
.subscribe(res => {
console.log('start download:',res);
var url = window.URL.createObjectURL(res.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
This is HTML part:
<button class="btn btn-primary" (click)="downloadFile()"><i class="fa fa-file-pdf-o"></i> Download</button>

OpenTok, How to switch publisher source from screen capturer to camera and vice versa?

I am trying to implement the feature that allows to switch between screen sharing capture and camera in the middle of the video session in an Android app. I use OpenTok SDK 2.5 for Android.
I have researched OpenTok examples (OpenTok samples) and figured they show only one feature per program sample.
Question: Should code supply two Publishers (one equipped with Camera and one with Screensharing capturer) and switch them, for example
session.unpublish();
if (currentIsCamera) {
session.publish(screenSharingPublisher);
}
else {
session.publish(cameraPublisher);
}
or better stick with single Publisher and flip between the BaseVideoCapturer and ScreensharingCapturer as I need?
mPublisher.setPublishVideo(false);
BaseVideoCapturer bvc = mPublisher.getCapturer();
if(bvc != null){
bvc.destroy();
}
//intent to start picture capture (Ex. ACTION_IMAGE_CAPTURE)
When you resume after taking the picture, you will need to initialize again
BaseVideoCapturer bvc = mPublisher.getCapturer();
if(bvc != null){
if(bvc.isCaptureStarted() == false){
bvc.init();
bvc.startCapture();
mPublisher.setPublishVideo(true);
}
}
This sample I took from the solution setPublishVideo(false) does not free the Camera
I suspect that unpublish/publish would break the session and that is not what I want.
P.S.Sorry for my English it is not my mother language.
On document Ready call the video publish method
var apiKey = '<APP_KEY>';
var sessionId = '<Session ID >';//Server Side Values
var token = '<Token >';//Server Side Values
var isModerator = <Yes/No>;//Handle it on server Side
var publisher;
var screenPublisher;
var streamMode = "camera";
session = OT.initSession(apiKey, sessionId);
publishVideo();
sessionEvents(publisher);
connectSession();
Html Code
<div id="subscribers" class="container-fluid show-controls">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div classs="live-stream">
<div class="caller-list">
<ul>
<li class="">
<div id="publisher" class="draggable user-camscreen">
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="controls" id="">
<div>
<button id="btnShareScreen" data-screen="0" class="">
<img src="~/Content/img/Student/screenshare.svg" class="screenshare" />
</button>
<p class="mb-none mt-xs text-sm line-height-xs text-white">Screen</p>
</div>
</div>
On camera/screen switch button click call
/*
Switching between camera and screen
*/
$("#btnShareScreen").on("click", function () {
el = $(this);
if (el.data('screen') == 0) {
//Publish Screen
publishScreen();
connectSession();
el.data('screen', '1');
el.find('img').attr('src', '/Content/img/Student/video-icon.svg');
el.parent().find('p').html("Camera");
}
else {
publishVideo();
connectSession();
el.data('screen', '0');
el.find('img').attr('src', '/Content/img/Student/screenshare.svg');
el.parent().find('p').html("Screen");
}
});
All Methods
function publishVideo() {
console.log(screenPublisher);
if (screenPublisher != undefined) {
endStream(screenPublisher);
}
createPublisherDiv();
publisher = OT.initPublisher('publisher', function (error) {
if (error) {
// Look at error.message to see what went wrong.
} else {
session.publish(publisher, function (error) {
if (error) {
// Look error.message to see what went wrong.
} else {
streamMode = "camera";
}
});
}
});
}
function publishScreen() {
OT.checkScreenSharingCapability(function (response) {
if (!response.supported || response.extensionRegistered === false) {
// This browser does not support screen sharing.
$.alert({
title: 'Alert!',
content: 'Your Browser Does Not Support Screen Sharing',
});
} else if (response.extensionInstalled === false) {
// Prompt to install the extension.
} else {
//Screen sharing available
endStream(publisher);
createPublisherDiv();
const publish = Promise.all([
OT.getUserMedia({
videoSource: 'screen'
}),
OT.getUserMedia({
videoSource: null
})
]).then(([screenStream, micStream]) => {
return screenPublisher = OT.initPublisher('publisher', {
videoSource: screenStream.getVideoTracks()[0],
audioSource: micStream.getAudioTracks()[0],
fitMode: "contain"
});
});
publish.then(screenPublisher => {
session.publish(screenPublisher, function (error) {
if (error) {
// Look error.message to see what went wrong.
} else {
streamMode = "screen";
}
});
}).catch(handleError);
}
});
}
function endStream(streamPublisher) {
session.unpublish(streamPublisher, function () {
//Call back
});
}
function connectSession() {
session.connect(token, function (error) {
if (error) {
console.error('Failed to connect', error);
}
});
}
function sessionEvents(streamPublisher) {
session.on({
sessionConnected: function (event) {
// Publish the publisher we initialzed earlier (this will trigger 'streamCreated' on other
// clients)
session.publish(streamPublisher, function (error) {
if (error) {
console.error('Failed to publish', error);
} else {
console.log("Publish success");
}
});
},
// This function runs when another client publishes a stream (eg. session.publish())
streamCreated: function (event) {
// Create a container for a new Subscriber, assign it an id using the streamId, put it inside
// the element with id="subscribers"
console.log(event.stream);
var subOptions = {
width: '100%', height: '100%'
};
var subContainer = document.createElement('div');
subContainer.id = 'stream-' + event.stream.streamId;
document.getElementById('subscribers').appendChild(subContainer);
// Subscribe to the stream that caused this event, put it inside the container we just made
subscriber = session.subscribe(event.stream, subContainer, subOptions, function (error) {
if (error) {
console.error('Failed to subscribe', error);
}
});
}
});
}
/*
OpenTok Unpublish Methods removes publisher div.That's why dynamically creating div
*/
function createPublisherDiv() {
$('.caller-list').find('li').empty();
var html = '<div id="publisher" class="draggable user-camscreen"></div>';
$('.caller-list').find('li').append(html);
}
function handleError(err) {
if (err) console.log(err.message);
}

choose image from android image gallery - PhoneGap not working

For Android in PhoneGap 2.8.0:
I need to get image from phone gallery and need to insert in app...
My code:
HEAD:
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<link rel="stylesheet" href="css/jquery.mobile-1.0rc1.min.css" />
<link rel="stylesheet" href="css/styles.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.0rc1.min.js"></script>
<script src="js/cordova.js"></script>
HTML:
<button data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Browse Photos</button>
<div id="photos"></div>
SCRIPT:
function onPhotoURISuccess(imageURI) {
var img = $('<img />');
img.attr('src', imageURI);
img.appendTo('#photos');
}
But its not working....how can i do this?
error that i got in console
file:///android_asser/www/index.html: Uncaught typeerror : cannot read property 'PHOTOLIBRARY' of undefined
Uncaught typeerror : [Object Object] has no method 'split' at file:///android_asset/www/js/jquery.mobile-1.0rc1.min.js
after i removed the jquery and jquery-mobile its working... any problem with jQuery with phonegap?
Thanks in advance
I have implemented this code...recently..check this
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoURISuccess(imageURI)
{
console.log(imageURI);
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
function onPhotoDataSuccess(imageURI)
{
var imgProfile = document.getElementById('imgProfile');
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1)
{
getLocation();
}
movePic(imageURI);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function movePic(file)
{
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
function resolveOnSuccess(entry)
{
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys)
{
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory)
{
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
function successMove(entry)
{
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error)
{
alert(error.code);
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
</script>
My html
<button onclick="capturePhoto();">Capture Photo</button>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Gallery!!</button>
try this link i hope it might be help you
http://tympanus.net/codrops/2010/05/27/awesome-mobile-image-gallery-web-app/
See the api
http://docs.phonegap.com/en/2.8.0/index.html
and you also try like
if Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.
Hi blow is working code for Camera and gallery.
I use different function for both purpose because using the device capture you can capture the multiple image .
i hope it will help you.
<select>
<option>--Select--</option>
<option onclick="GetImage(1)">Camera</option>
<option onclick="GetImage(2)">Library</option>
<option onclick="GetImage(3)">Album</option>
</select>
//// fuction to select which type of upload you want to perform
GetImage(index)
{
switch (index)
{
case 1:
captureImage();
break;
case 2:
getPhoto('pictureSource.PHOTOLIBRARY');
break;
case 3:
getPhoto('pictureSource.SAVEDPHOTOALBUM');
break;
}
}
//// fuction calle from camera capture success
function captureSuccess(mediaFiles) {
var i, len;
debugger;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
//// function to camputure image from camera
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, capturetError, { limit: 1 });
}
//// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your s url
var objUrl =www.xyx.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
//// fuction to capture image from Gallery or PHOTOLIBRARY
function getPhoto(source) {
// Retrieve image file location from specified source
var cameraSource;
if (source = "pictureSource.PHOTOLIBRARY") {
cameraSource = pictureSource.PHOTOLIBRARY;
}
if (source = "pictureSource.PHOTOLIBRARY") {
cameraSource = pictureSource.SAVEDPHOTOALBUM;
}
navigator.camera.getPicture(CaptureImageSuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: cameraSource
});
}
//// Upload files to server from Gallery
function CaptureImageSuccess(fileURI) {
////your service url
var objUrl =www.xyx.com;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1)+".jpg";
options.mimeType = "image/jpeg";
options.params = {}; // if we need to send parameters to the server request
var ft = new FileTransfer();
//ft.upload(fileURI, encodeURI(), win, fail, options);
ft.upload(fileURI,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
};

Categories

Resources