I am having problems with Apache Cordova and Android. I have some code to send one picture to server, from an Android cellphone, but it doesn't work. I have tested the ajax and php code on the server, and it works, but when I try from the cellphone it does not.
app.js:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
var image = "";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType: destinationType.DATA_URL
});
}
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
image = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function submitFunction() {
var dataString = 'image='+encodeURIComponent(image);
$.ajax({
type: "POST",
url: "//192.0.1.2/testing/test.php",
data: dataString,
cache: false,
error: function(){
ShowStatus( "AJAX - error()" );
document.getElementById("result").innerHTML = 'Error';
},
beforeSend: function() {
document.getElementById("result").innerHTML = 'Enviando Data';
},
success: function(result){
document.getElementById("result").innerHTML = result;
}
});
}
test.php:
<?php
header('Access-Control-Allow-Origin: *');
require'connection.php';
$mysqli = conectarse();
$res = $mysqli->query("INSERT INTO imagenes (image) VALUES
('".$_POST['image']."')");
$mysqli->query($res);
if (!$res) {
printf("Errormessage: %sn", $mysqli->error);
}
?>
This code has the following dependencies:
cordova.js
jquery.min.js
Related
using cordova media-capture and file-transfer plugin I try to make an app to record video and upload on server. After recording video I call the upload function and it showing the success message in success callback function. But no file uploaded in server. Here my code.
$(document).ready(function(){
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:1});
}
var captureSuccess = function(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
};
var captureError = function(error) {
alert('error');
console.log(error);
};
/********* File Upload **********/
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://myserver.com/test.php",
function(result) {
alert('success');
},
function(error) {
alert('error');
},
{ fileName: name, fileKey: "file" });
}
My php code is
<?php
if($_FILES['file']['size'] > 0) {
$path = $_SERVER['DOCUMENT_ROOT']."/audior/app/";
$tmpname1 = $_FILES['file']['tmp_name'];
$ptname1 = $_FILES['file']['name'];
move_uploaded_file($tmpname1, $path . $ptname1);
echo 'success';
}
?>
You have to create a FileUploadOptions object
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = name;
then use it on the upload function
ft.upload(path,
"http://myserver.com/test.php",
function(result) {
alert('success');
},
function(error) {
alert('error');
},
options);
You can also change the
function(result) {
alert('success');
}
to
function(result) {
alert(result);
}
Just to check if the server is telling you something.
If you are getting the success callback the problem should be on the PHP script.
I use this one that returns the url of the uploaded file
<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], "./" . $_FILES["file"]["name"]);
echo "http://" . $_SERVER['SERVER_NAME'] . "/" . $target_file;
?>
I have a service upload imageto amazon s3 after i sign it with my own backend using cordova file-transfer plugin.
I call this service after taking a picture using cordova camera plugin to upload the taken picture to the s3 bucket.
The app sign correctly with my own backend but when it trigger the function upload i get the error i defined in the title.
This is the service that it call an end point in my backend to sign the file and then upload the image to amazon s3:
//Image upload Service
.factory('S3Uploader', function($q, $window, $http, $ionicPopup, API_URL) {
var signingURI = API_URL + "s3signing";
function upload(imageURI, fileName) {
document.addEventListener('deviceready', function() {
console.log('Uploading ' + fileName + ' to S3');
var deferred = $q.defer(),
ft = new FileTransfer(),
options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
console.log('Requesting signed doc ' + signingURI);
$http.post(signingURI, {
"fileName": fileName
})
.success(function(data) {
console.log('Got signed doc: ' + JSON.stringify(data));
options.params = {
"auth": true,
"key": fileName,
"AWSAccessKeyId": data.awsKey,
"acl": "public-read",
"policy": data.policy,
"signature": data.signature,
"Content-Type": "image/jpeg"
};
ft.upload(imageURI, "https://" + data.bucket + ".s3.amazonaws.com/",
function(e) {
console.log("Upload succeeded");
console.log(JSON.stringify(e));
deferred.resolve(e);
$ionicPopup.alert({
title: 'great',
content: 'The image upload to amazon success'
});
},
function(e) {
deferred.reject(e);
$ionicPopup.alert({
title: 'Oops',
content: 'The image upload failed to amazon'
});
}, options);
})
.error(function(data, status, headers, config) {
console.log(JSON.stringify(data));
console.log(status);
$ionicPopup.alert({
title: 'Oops',
content: 'The image upload failed to sign with node'
});
});
return deferred.promise;
}, false); //device ready
}
return {
upload: upload
}
})
and here is the controller code where am calling the camera plugin and in the success of taking the picture am calling the upload function from the S3Uploader service:
.controller('newItemCtrl', function($scope, $http, $ionicPopup, $timeout, $cordovaCamera, API_URL, me, S3Uploader) {
$scope.selectPicture = function() {
document.addEventListener('deviceready', function() {
var options = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
};
$cordovaCamera.getPicture(options).then(function(imageURI) {
$scope.imageSrc = imageURI;
// upload to Amazon s3 bucket
var fileName = new Date().getTime() + ".jpg";
S3Uploader.upload(imageURI, fileName).then(function() {
alert("upload to S3 successed");
});
}, function(err) {
alert(err);
});
}, false); // device ready
}; // Select picture
})
i get the erorr in this line of the controller:
S3Uploader.upload(imageURI, fileName).then(function() {
it's also important to mention am using crosswalk with my ionic app.
Your current implementation of S3Uploader.upload does not return a promise, it returns nothing. Move your declaration and return of the promise to directly inside the S3Uploader.upload function and not nested inside the document.addEventListener code.
Change your code to something like:
.factory('S3Uploader', function($q, $window, $http, $ionicPopup, API_URL) {
var signingURI = API_URL + "s3signing";
function upload(imageURI, fileName) {
var deferred = $q.defer()
document.addEventListener('deviceready', function() {
// Removed for brevity
}, false);
return deferred.promise;
}
return {
upload: upload
}
})
You are creating and returning your deferred object and it's promise from an event listener. Not the upload factory method.
Something along these lines is what you need:
.factory('S3Uploader', function($q) {
function upload() {
var deferred = $q.defer();
// listener logic
return deferred.promise;
}
return {
upload : upload
}
});
You will have problems with this, as you will want a new deferred object for each time the listener is fired. Adding a listener to a factory method to perform something seems like a bad pattern to me. The event should wrap the invocation of the factory method.
I tried many ways and referred many questions here but still my camera is not launching.Help me in this.I checked manifest and config xml files.there is no error in that.Can any one give me working example for cordova camera.
<script>
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
function capturePhoto() {
alert("varun");
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA });
}
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
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);
};
Here is my phonegap code. This code is for taking the picture as well as save the picture also:
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo and Save</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready to be used!
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
var date = ""
var d = new Date();
date = "" + d.getDate() + "-" + (d.getMonth() + 1) + "-"
+ d.getFullYear();
alert(date)
//alert(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
alert("data:image/jpeg;base64," + imageData)
//This part is for saving the capture photo
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
alert("image/" + date + ".jpeg")
fileSystem.root.getFile("image/" + date + ".jpeg", {
create : true,
exclusive : false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
var data = "data:image/jpeg;base64," + imageData;
writer.write(data);
}
function fail(error) {
alert("error")
console.log(error.code);
}
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
var largeImage = document.getElementById('largeImage');
// Unhide image elements
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 50,
destinationType : destinationType.DATA_URL
});
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 20,
allowEdit : true,
destinationType : destinationType.DATA_URL
});
}
// A button will call this function
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality : 50,
destinationType : destinationType.FILE_URI,
sourceType : source
});
}
// Called if something bad happens.
function onFail(message) {
alert('Failed because: ' + message);
}
function savePhoto(source) {
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button>
<br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button>
<br>
<button onclick="savePhoto();">Save The Photo In Server</button>
<br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From
Photo Library</button>
<br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From
PhotoAlbum</button>
<br>
<img style="display: none; width: 60px; height: 60px;" id="smallImage"
src="" />
<img style="display: none;" id="largeImage" src="" />
</body>
</html>
I am taking a picture and trying to save it like this but it is saving as a file not as a picture(binary).so after saving the picture its not opening.How can i save it with proper fromat so that i can open it as a picture ?
I did it this way:
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI, });
}
function onPhotoDataSuccess(imageURI) {
var gotFileEntry = function(fileEntry) {
//alert("got image file entry: " + fileEntry.fullPath);
var gotFileSystem = function(fileSystem) {
fileSystem.root.getDirectory("MyAppFolder", {
create : true
}, function(dataDir) {
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
console.log("Saved image" + dataDir);
// copy the file
fileEntry.moveTo(dataDir, newFileName, null, fsFail);
}, dirFail);
};
// get file system to copy or move image file to
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem,
fsFail);
};
// resolve file system for image
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, fsFail);
// file system fail
var fsFail = function(error) {
alert("failed with error code: " + error.code);
};
var dirFail = function(error) {
alert("Directory error code: " + error.code);
};
}
Hope it helps you!
If you are ok to save image in photo gallery, then try following code :
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType : destinationType.FILE_URI,
saveToPhotoAlbum : true,
});
}
function save(){
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("pic.jpg", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
var photo = document.getElementById("image");
writer.write(photo.value);
}
function fail(error) {
console.log(error.code);
}