I'm developing a PhoneGap app with file upload and I'm using the following script which when I tap on upload picture it gives me an error Upload failed Code=3.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<style type="text/css">
div {border: 1px solid black;}
input {width: 100%;}
</style>
<script src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var options = new FileUploadOptions();
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<h3>PhoneGap Camera Upload Demo</h3>
<div>
<h3>Server URL for upload.php:</h3>
<input id="serverUrl" type="text" value="http://usersamplesite.com/folder" />
</div>
<br/>
<!-- Camera -->
<div>
<h3>Camera:</h3>
<b>Status:</b> <span id="camera_status"></span><br>
<b>Image:</b> <img style="width:120px;visibility:hidden;display:none;" id="camera_image" src="" />
</div>
<!-- Actions -->
<div>
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
<!-- Server pictures -->
<div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
</div>
<!-- Actions -->
<div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
</body>
</html>
I found out here that, I should use the below script to make it work, but I don't know where to put it in the script and I need help, I'm new to PhoneGap.
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
Add true in as last param of Upload Function
upload(filePath, server, successCallback, errorCallback, options, true);
Try putting options.header inside uploadPicture() rather than putting it at start of your document.
function uploadPicture() {
......
......
if(server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, success, failure, options, true);
}
}
Related
I'm trying to implement the login action using the twitter acount in my cordova app.
I have found a script using Childbrowser.js file to do it but it's not supported anymore so that I am trying to do it using the inappBrowser plugin instead of the childbrowser.
I succeeded in opening the login interface but after the login it redirect me to a web page. How can I redirect to my html local page? can I get ignore the redirect url and just get the access token?
this is the code that I am using:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
return ('here test');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){alert('stop: ' + loc.url);
// Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
alert('ok entred');
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.indexOf("http://127.0.0.1:81/?") >= 0) {
// Parse the returned URL
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
window.plugins.childBrowser.close();
},
function(data) {
alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
Actually there is error in your code you have to fix it:
the https://api.twitter.com/1/account/verify_credentials.json?skip_status=true' is no more used change it to 1.1.
also change the way you close your inappbrowser.
this code works for me try it:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
retiurn ('hhhh');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text,'_blank', 'location=no'); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){//alert('stop: ' + loc.url);
Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
// alert(loc.url);
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.url.indexOf("http://127.0.0.1:81/?") >-1) {
// Parse the returned URL
var index, verifier = '';
var params = loc.url.substr(loc.url.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
// alert(verifier)
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
// alert('key'+twitterKey);
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
cb.close();
},
function(data) {
// alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1.1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
Phonegap: 2.9.0
Android: 4.4.2
Device: Nexus 5
I moved the "assets\www" files to my host, and "super.loadUrl("http://mydomain.com");", Because it's easy to maintain, lucky, Phonegap works!
But it can not uploads files, why? Here is my codes:
MainActivity.java
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("http://mydomain.com");
}
}
index.php (on host)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady()
{
console.log("device ready");
// Do cool things here...
}
function getImage()
{
// Retrieve image file location from specified source
navigator.camera.getPicture
(
uploadPhoto,
function(message)
{
alert('get picture failed');
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(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, "upload.php", win, fail, options);
}
function win(r)
{
console.log("Code = " + r.responseCode.toString()+"\n");
console.log("Response = " + r.response.toString()+"\n");
console.log("Sent = " + r.bytesSent.toString()+"\n");
alert("Code Slayer!!!");
}
function fail(error)
{
alert("An error has occurred: Code = " + error.code);
}
</script>
</head>
<body>
<button onclick="location.replace(location.href);">Refresh</button>
<button onclick="getImage();">Upload a Photo</button>
</body>
</html>
</html>
upload.php (on host)
<?php
print_r($_FILES);
?>
I click the button and select a photo, it alerts "An error has occurred.Code = 2", how to solve this problem?
Thanks for help!
You will want to specify a full path to the upload.php file, example:
ft.upload(imageURI, "http://www.mydomain.com/upload.php", win, fail, options);
When I use html5 'getUserMedia' API to access acamera on the android(4.0) phone, it comes out "front camera", but I want to open "back camera". Sample code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Html5 Mobile Carema</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(init);
function init() {
try {
window.URL = window.URL || window.webkitURL || window.msURL
|| window.oURL;
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({
video : true
}, successsCallback, errorCallback);
} catch (err) {
// Tries it with old spec of string syntax
navigator.getUserMedia('video', successsCallback, errorCallback);
}
$(":button").click(function() {
slap();
});
}
function slap() {
var video = $("#myVideo")[0];
var canvas = capture(video);
$("#result").empty();
$("#result").append(canvas);
//alert();
var imgData = canvas.toDataURL('image/png;base64,');
//var imgData = canvas.toDataURL("image/png");
var imgData = imgData.substring(22);
//blb = dataURItoBlob(imgData);
//sendMsg(blb);
}
function errorCallback(err) {
}
function successsCallback(stream) {
$("#myVideo").attr("src", window.webkitURL.createObjectURL(stream));
}
function capture(video) {
var canvas = document.createElement('canvas');
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, 160, 120);
return canvas;
}
</script>
</head>
<body>
<video id="myVideo" autoplay="autoplay"></video>
<br> <input type="button" value="capture" />
<br><div id="result" style="width: 145px"></div>
<div>
<p id="resultMsg" style="color: red"></p>
<p id="decodeTime" style="color: green"></p>
</div>
</body>
</html>
I don't know how to access specific camera on android phone, anyone who knows? thanks
There is now the ability to specify a camera in the latest specification with the facingMode property: http://www.w3.org/TR/mediacapture-streams/#idl-def-VideoFacingModeEnum
This property is an optional part of the MediaStreamConstraints object that is the first argument of the getUserMedia method.
Here's a simplified example from the spec:
var supports = navigator.mediaDevices.getSupportedConstraints();
if (!supports["facingMode"]) {
// Handle lack of browser support if necessary
}
var gotten = navigator.mediaDevices.getUserMedia({
video: {
facingMode: {exact: "environment"}
}
});
The value environment means the back camera of the device. Other values are user, left and right.
Note that support for this varies depending on the browser/browser version.
See function gotSources(sourceInfos) in the code below
<!--
Based on Motion Detector Demo Created by Ákos Nikházy.
If you use this app please link this demo http://motion-detector.nikhazy-dizajn.hu/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Frame capture demo</title>
</head>
<body>
<header>
<h1>Motion Detection</h1>
<h4>with HTML5 API using .getUserMedia()</h4>
</header>
<video autoplay></video>
<hr>
<canvas id="savePhoto"></canvas>
<script>
function hasGetUserMedia() {
//returns true if supported
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
function onSuccess(stream) {
//If we can stream from camera.
var source;
//Get the stream. This goes to the video tag
if (window.URL) {
source = window.URL.createObjectURL(stream);
} else if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera and Firefox
}
//Set up video tag
video.autoplay = true;
video.src = source;
//We try to find motion in every X second
setInterval(function() {
motionDetector();
}, sampling);
}
function onError() {
//if we fail (not supported, no camera etc.)
alert('No stream, no win. Refresh.');
}
function saveImage(canvasToSave) {
//create image from canvas
dataUrl = canvasToSave.toDataURL();
imageFound = document.createElement('img');
imageFound.src = dataUrl;
document.body.appendChild(imageFound);
}
function motionDetector() {
ctxSave.drawImage(video, 0, 0, savePhoto.width, savePhoto.height);
}
/*After all those functions lets start setting up the program*/
//Set up elements. Should be a ini() but I don't care right now
var video = document.querySelector('video'); //the video tag
var savePhoto = document.getElementById('savePhoto'); //the possible saved image's canvas
var ctxSave = savePhoto.getContext('2d'); //the latest image from video in full size and color
var sampling = 1000; //how much time needed between samples in milliseconds
var videoSourceInfo = null;
//We need this so we can use the videoWidth and ...Height, also we setup canvas sizes here, after we have video data
video.addEventListener("loadedmetadata", function() {
console.log(video.videoWidth + ":" + video.videoHeight)
savePhoto.width = video.videoWidth;
savePhoto.height = video.videoHeight;
});
function start() { //Start the whole magic
if (hasGetUserMedia()) {
//it is working?
navigator.getUserMedia
|| (navigator.getUserMedia = navigator.mozGetUserMedia
|| navigator.webkitGetUserMedia
|| navigator.msGetUserMedia);
var videoSourceInfoId = videoSourceInfo.id;
var constraints = {
video : {
optional: [{sourceId: videoSourceInfoId}]
},
toString : function() {
return "video";
}
};
navigator.getUserMedia(constraints, onSuccess, onError);
} else {
//no support
alert('getUserMedia() is not supported in your browser. Try Chrome.');
}
}
function gotSources(sourceInfos) {
for (var i = sourceInfos.length-1 ; i >= 0; i--) { // get last camera index (supposed to back camera)
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video') {
videoSourceInfo = sourceInfo;
console.log('SourceId: ', videoSourceInfo.id);
start();
break;
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources); // async task
}
</script>
</body>
</html>
Hi I think this works with you
<script>
var gum = mode =>
navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: mode}}})
.then(stream => (video.srcObject = stream))
.catch(e => log(e));
var stop = () => video.srcObject && video.srcObject.getTracks().forEach(t => t.stop());
var log = msg => div.innerHTML += msg + "<br>";
</script>
<button onclick="stop();gum('user')">Front</button>
<button onclick="stop();gum('environment')">Back</button>
<div id="div"></div><br>
<video id="video" height="320" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
facingMode??
https://github.com/webrtcHacks/adapter/issues/820
https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode
I'm new here and have a problem in last week:
I made an app in phonegap(cordova2.1.0) and this is the code:
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
HTML code:
Image:
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
well: part of this code is not mine.
QUESTION
there is no error alert
the alert says everything was done. image uploaded and the bytes
in my msql the image has no the extension(.jpg) only the name
and in the images folder theres nothing uploaded
i whitelisted everything,
can anibody help me?
I don't know wat else to do..
thanks in advance
by the way in eclipse log everithing shows ok too,
in android 2.3 actual phone the same thing, but the image is not there..
i would like to ask you..
i have a code... using phonegap.. but i was confused about how to call / crop the image after take it from camera / file manager...
here the code...
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="js/jquery.mobile-1.0.min.css" />
<script src="js/jquery-1.6.4.min.js"></script>
<script src="js/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.1.0.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
window.location.hash = "#page2";
/*document.getElementById('camera_status').innerHTML = "Success"; */
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, targetWidth: 1153, targetHeight: 385
}
);
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
window.location.hash = "#page2";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, targetWidth: 1153, targetHeight: 385, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
$.mobile.showPageLoadingMsg();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
viewUploadedPictures();
$.mobile.hidePageLoadingMsg();
window.location.hash = "#page3";
}, function(error) {
$.mobile.hidePageLoadingMsg();
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<!-- Page 1 -->
<div data-role="page" id="page1">
<!-- Page 1 Header -->
<div data-role="header">
<h1>Ambil Gambar</h1>
</div>
<!-- Page 1 Content -->
<div data-role="content">
<center>
<a href="javascript:void(0)" onclick="takePicture();">
<img src="image/camera.png" width="150px" height="150px">
</a>
<br>
<br>
<b>Atau</b>
<br>
<br>
<a href="javascript:void(0)" onclick="selectPicture();">
<img src="image/upload.png">
</a>
</center>
</div>
<!-- Page 1 Footer -->
<div data-role="footer">
<h4>Footer 1</h4>
</div>
</div>
<!-- Page 2 -->
<div data-role="page" id="page2">
<!-- Page 2 Header -->
<div data-role="header">
<h1>Header 2</h1>
</div>
<!-- Page 2 Content -->
<div data-role="content">
<img style="width:100%;visibility:hidden;display:none;" id="camera_image" src="" />
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
<input id="serverUrl" type="text" value="http://kiosban.com/android/camera/upload.php" />
Status : <span id="camera_status"></span>
Skip
</div>
<!-- Page 2 Footer -->
<div data-role="footer">
<h4>Footer 2</h4>
</div>
</div>
<!-- Page 3 -->
<div data-role="page" id="page3">
<!-- Page 3 Header -->
<div data-role="header">
<h1>Header 3</h1>
</div>
<!-- Page 3 Content -->
<div data-role="content">
<div id="server_images"></div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
<!-- Page 2 Footer -->
<div data-role="footer">
<h4>Footer 2</h4>
</div>
</div>
</body>
</html>
I want to call image crop on #page2, so there is an upload button to upload the cropped image...
can anybody help me do that??
PhoneGap does not have built-in crop features. Some platforms (iPhone for sure) allows the user to crop the picture after taking it with the camera but before it would be returned to your JavaScript code if you pass the allowEdit = true parameter to getPicture. But you won't have control here from your script.
You'll have to implement the cropping feature yourself from JavaScript. It is easier then expected with the canvas tag of HTML5. You can find a pretty tutorial here.
I found the solution for this(it is too late but used for someone like me) but after taking image you need to pass the image path to the plugin(Native android) for croping.
put the following code in your image capture or pick image from gallery(in your index.html):
navigator.camera.getPicture(function(imageURI){
window.resolveLocalFileSystemURI(imageURI, function(fileEntry){
fileEntry.file(function(fileObj) {
var imagedata ="sample/new001.img";
// able to get the image location using phonegap
cropImage.createEvent(imagedata);
});
}, fail);
}, fail, { quality: 50,
destinationType: destinationType.NATIVE_URI,
sourceType: pictureSource.PHOTOLIBRARY
});
after that crop.image.js should be like (include this file name in your index.html)
var cropImage = {
createEvent: function(fileName) {
cordova.exec(
null, // success callback function
null, // error callback function
'CropImage', // mapped to our native Java class called "CropImage"
'GetImageName', // with this action name
[fileName]
);
}
}
Your java code is like
public class CropImage extends CordovaPlugin{
public final String ACTION_GET_IMAGE_NAME = "GetImageName";
Uri myUri;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
// Log.e(TAG,"Inside Version plugin.");
boolean result = false;
if(action.equals(ACTION_GET_IMAGE_NAME)) {
try {
myUri = Uri.parse(args.getString(0));
cropCapturedImage(myUri);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = true;
}
return result;
}
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// for save the image in same location with same name.
File f = new File(Environment.getExternalStorageDirectory()+"your image location here");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
cropIntent.putExtra("output", Uri.fromFile(f));
cropIntent.putExtra("return-data", false);
//start the activity - we handle returning in onActivityResult
this.cordova.startActivityForResult((CordovaPlugin) this,cropIntent, 2);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//Log.e("final", String.valueOf(requestCode));
/*if(requestCode == 2){
//Create an instance of bundle and get the returned data
Bundle extras = intent.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
}*/
}
}
Don't forget to add this class in your CONFIG.XML and add the necessary permissions. Feel free to ask any doubts.