I have a problem saving an image in JSON. I can access the mobile camera using this code:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// PhoneGap is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoFileSuccess(imageData) {
// Get image handle
console.log(JSON.stringify(imageData));
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
location.href = "#pageone";
}
function capturePhotoWithFile() {
navigator.camera.getPicture(onPhotoFileSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onFail(message) {
alert('Failed because: ' + message);
}
My problem is that I have a form with text that should take and save a picture. This is my code that adds and saves the form without the image:
function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname : $("#fname").val(),
lname : $("#lname").val(),
address : $("#address").val(),
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}
My question is, how can I insert the image file in this function add()? Thanks a lot!
Assuming that Add() gets called after onPhotoFileSuccess(), then you can do this in your Add() function (see below). It will be a data url - meaning the url has all of the image data encoded within it.
function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname : $("#fname").val(),
lname : $("#lname").val(),
address : $("#address").val(),
photoData: $("#smallImage").attr("src")
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}
Related
I'm Trying to build an app with Cordova. With the app you should take pictures, these pictures needs to be uploaded to a database together with the location where the picture is taken.
The app on default shows a x number of the most nearest taken pictures to your live location.
Beneath here i post the javascript code i have right now, most of the code is from Cordova self. Is it better to modify this code or start over?
I can now access the camera and take a picture, but how do i upload this picture together with the location to a database?
And how can load the nearest pictures from the database?
var Latitude = undefined;
var Longitude = undefined;
window.onload = function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
navigator.notification.alert("ready");
document.getElementById("camera").addEventListener
("click", cameraTakePicture);
}
function cameraTakePicture() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData, imageURI) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
getLocation();
navigator.notification.alert(image.src);
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
function getLocation() {
navigator.notification.alert("start locatie");
navigator.geolocation.getCurrentPosition(onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });
}
var onPicturesSuccess = function (position) {
Latitude = position.coords.latitude;
Longitude = position.coords.longitude;
getPictures(Latitude, Longitude);
}
function getPictures(latitude, longitude) {
//Load pictures which are the nearest
}
var onPicturesWatchSuccess = function (position) {
var updatedLatitude = position.coords.latitude;
var updatedLongitude = position.coords.longitude;
if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
Latitude = updatedLatitude;
Longitude = updatedLongitude;
getPictures(updatedLatitude, updatedLongitude);
}
}
// Error callback
function onPicturesError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Watch your changing position
function watchPicturePosition() {
return navigator.geolocation.watchPosition
(onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
}
You can use Cordova File Transfer Plugin to upload your photos to your backend service (DB). In FT Plugin you can add some additional headers, or properties e.g. LAT and LON properties.
Since you didn't specifically mention it, I'm going to assume you have access to jQuery inside your Cordova app.
Inside your onSuccess you have to make an AJAX call that submits the image and location to your PHP server. Below is an example:
var request = {
'url': 'path/to/your/php/script.php',
'method': 'POST',
'data': {
'image': image.src,
'location': getLocation()
}
}
$.ajax(request).done(function(response) {
// request is done
});
Your PHP server script will have to take the incoming data and save it to your database.
EDIT: Changed win() function and added am image corresponding to it's result.
I am having trouble uploading image to a webserver using phonegap.
This is the code that I have for the app:
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 onPhotoURISuccess(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;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://www.tayabsoomro.me/upload.php", win, fail, options);
}
function win(r){
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error){
alert("An error occured while uploading image: " + error.code);
}
The code triggers win() function and shows the JSON data of the result when the image is captured so at least it doesn't fail().
And here's an image of what win() function alerts.
and this is what my upload.php looks like:
<?php
print_r($_FILES);
$new_image_name = "myimg.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$new_image_name);
?>
Ensure that you have all the appropriate (Read/Write) permissions set to your target folder uploads/ where you try to upload your files.
Hope this helps!.
I am new to to the developing phonegap application. I need to choose the picture from the photolibrary after that need to store the path of the selected picture in localStorage, still this i did using destinationType as FILE_URI then i need to call another function which helps to converting the selected picture into base64 string by using File Reader's property readAsDataURL and upload that string to the server. The first part is working fine but that second part is not working please help me to solve this problem.
My HTML page is,
<button class="button" onclick="uploadImage();">From Photo Library</button>
<img style="display:none;width:60px;height:60px;" id="largeImage" src="" />
<button class="button" onclick="syncData();">Sync Data</button>
My Script.js is,
var pictureSource; // picture source
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
var pictureSource = navigator.camera.PictureSourceType;
var destinationType = navigator.camera.DestinationType;
function uploadImage(){
alert('called upload pic');
//Using library
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,
destinationType: destinationType.FILE_URI, sourceType: pictureSource.PHOTOLIBRARY});
}
function onFailcapturePhoto(message) {
alert("Message = " + message);
}
function uploadPhoto(imageURI) {
if(!localStorage.imageArray) {
var imageArray = [];
imageArray.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imageArray));
alert(JSON.stringify(imageArray));
} else {
var imagefile = JSON.parse(localStorage.imageArray);
imagefile.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imagefile));
alert(JSON.stringify(imagefile));
}
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI; // here i can display the image
}
function syncData() {
var reader = new FileReader();
var selectedImageArray = [];
function readFile(index) {
alert('in read file'); // here i am getting alert
if( index >= JSON.parse(localStorage.imageArray).length ) return;
var file = JSON.parse(localStorage.imageArray)[index];
alert('file=='+file); // here i am getting path
reader.onloadend = function(e) {
// get file content
alert('in loadend');
selectedImageArray[index] = e.target.result;
alert('image data==:>'+selectedImageArray[index])
readFile(index+1);
}
if(file) {
alert('going to read'); // i got alert here, after this line i don't get anything
reader.readAsDataURL(file);
alert('reading finished');
} else {
alert('Your Browser does not support File Reader..');
}
}
readFile(0);
alert('before clear'+JSON.stringify(localStorage.imageArray));
localStorage.clear();
alert('after clear'+JSON.stringify(localStorage.imageArray));
}
Thanks & Regards,
Murali Selvaraj
By Following code i got answer for my question..
big thanks to this author..
my updated code is:
function uploadPhoto(imageURI) {
if (imageURI.substring(0,21)=="content://com.android") {
photo_split=imageURI.split("%3A");
imageURI="content://media/external/images/media/"+photo_split[1];
alert('new uri'+imageURI);
}
if(!localStorage.imageArray) {
var imageArray = [];
imageArray.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imageArray));
alert(JSON.stringify(imageArray));
} else {
var imagefile = JSON.parse(localStorage.imageArray);
imagefile.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imagefile));
alert(JSON.stringify(imagefile));
}
}
function syncData() {
var selectedImageArray = new Array();
function readFile(index) {
if( index >= JSON.parse(localStorage.imageArray).length ) {
if(selectedImageArray.length == 0) return;
$.ajax({
url : 'Here place your api', //your server url where u have to upload
type : 'POST',
dataType : 'JSON',
contentType : 'application/json',
data : JSON.stringify(selectedImageArray)
})
.done(function(res) {
alert('success='+res);
localStorage.clear();
})
.error(function(err) {
alert('error='+err);
});
} else {
var filePath = JSON.parse(localStorage.imageArray)[index];
window.resolveLocalFileSystemURI(filePath, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
selectedImageArray.push(evt.target.result);
readFile(index+1);
}
reader.onerror = function(evt) {
alert('read error');
alert(JSON.stringify(evt));
}
entry.file(function(f) {
reader.readAsDataURL(f)
}, function(err) {
alert('error='+err);
});
});
}
}
readFile(0);
}
i am capturing image with cordova using reference:
http://docs.phonegap.com/en/2.7.0/cordova_camera_camera.md.html
It's working fine. But when i click on save, the image is not saved/ stored in my phone.
Is there any extra js required apart from the code?
Or please tell me if there is any method to store image in a particular folder.
Thanks in advance.
Try like the following. It will save the image in the sample folder and also randomfilename should be you file name of taken image(generate new name every time using randomNumber generation or use the default camera returned file name).
navigator.camera.getPicture(function(imageData) {
var directory = "sampleApp/";
var randomFileName = "sampleimg.png"; // this should be the filename
saveImage(imageData,randomFileName,directory);
}, onFail, {
quality : 50,
destinationType : Camera.DestinationType.FILE_URI
});
function saveImage(imageData,fileName,directory){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function gotFile(fileSystem) {
fileSystem.root.getDirectory(directory, {create: true}, function fileSystemSuccess(fileSystem){
fileSystem.getFile("dummy.txt",{create: true,exclusive:false},function gotFileEntry(fileEntry){
var path = fileEntry.fullPath.replace("dummy.txt","");
fileEntry.remove();
var fileTransfer = new FileTransfer();
fileTransfer.download(imageData, path+""+fileName,function(theFile){
alert("File Downloaded Successfully");
},function(error){
alert("File Download Failed"+ error.code);
});
},fail);
});
}, fail);
}
function fail(e){
alert("Error Occured"+ e.code);
}
I am using titanium studio and i am trying to save am image from a POST request.
function buyImage(s){
var userName = Ti.App.Properties.getString('username');
var email = Ti.App.Properties.getString('email');
var encKey = Ti.App.Properties.getString('key');
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Key Text: " + this.responseData);
Titanium.Media.saveToPhotoGallery(this.responseData,{
success: function(e) {
Titanium.UI.createAlertDialog({
title:'Photo Gallery',
message:'Check your photo gallery for you image'
}).show();
},
error: function(e) {
Titanium.UI.createAlertDialog({
title:'Error saving',
message:e.error
}).show();
}
});
Titanium.UI.createAlertDialog({title:'Photo Gallery',message:'Photo saved to gallery'}).show();
},
onerror : function(e) {
Ti.API.info(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("POST", "http://somesite/create/save?userName="+userName+"&encryptionKey="+encKey+"&email="+email+"&recordId="+s);
// Send the request.
client.send();
The image says it saves ok and it says the responce data is a TiBlob but the image does not seem to save at all. When the same post is done in a post event in a browser you are prompted to download the image.
any ideas?