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);
Related
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);
}
}
I have created a phonegap app and I added Android platform to it. But unfortunately, deviceready event is not getting fired. It works fine on ripple emulator but it is not working on chrome (desktop) and on the android phone as well.
If I run it on chrome (desktop) or my Android L phone, I get the error gap:
["Device","getDeviceInfo","Device1231860141"]
and the browser as well as NetBeans hangs.
I have the cordova.js file in my www folder. I tried removing it, and the error goes away, but deviceready is still not fired.
The following is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320, user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" href="js/libs/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.css"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/libs/jquery/jquery.js"></script>
<script type="text/javascript">
function init(){
document.addEventListener("deviceready", onDeviceReady, true);
}
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
// Update acceleration every 3 seconds
var options = { frequency: 3000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
</head>
<body onload="init()">
</body>
</html>
deviceready is a cordova event it will not work in browser.
...
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady() {
startWatch();
}
...
</script>
</head>
<body onload="onDeviceReady()">
</body>
</html>
I was trying some cookbook samples of phonegap app(along with xui) to read write files to local storage(SD card), PhoneGap is so popular in its file io, but when I tried on the device it didn't do anything. I think somebody has encountered same things.
The code is shown below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<title>File Download</title>
<script type="text/javascript" src="xui.js"></script>
<script type="text/javascript" src="cordova-2.0.0.js"></script>
<script type="text/javascript" >
var downloadDirectory;
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
onFileSystemSuccess,
null
);
x$('#download_btn').on( 'click', function(e) {
download();
});
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory('my_downloads',{create:true},
function(dir) {
downloadDirectory = dir;
},fail);
}
function fail(error) {
x$('#message').html('We encountered a problem: ' + error.code);
}
function download() {
var fileURL = document.getElementById('file_url').value;
var localFileName = getFilename(fileURL);
x$('#message').html('Downloading ' + localFileName);
var fileTransfer = new FileTransfer();
fileTransfer.download(fileURL, downloadDirectory.fullPath + '/' + localFileName,
function(entry){
x$('#message').html('Download complete. File saved to: ' + entry.fullPath);
},
function(error){
alert("Download error source " + error.source);
}
);
}
// Obtain the filename
function getFilename(url) {
if (url) {
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1) {
return m[1] + '.' + url.split('.').pop();
}
}
return "";
}
</script>
</head>
<body>
<input type="text" id="file_url" value="http://blogs.adobe.com/adobeingovernment/files/2012/07/phonegap.jpg" />
<input type="button" id="download_btn" value="Download" />
<div id="message"></div>
</body>
</html>
I already reviewed android manifest file, it has all permission including write to external storage. Kindly advise.
I am trying to access a text file inside the www folder of one of my phonegap applications from the index.html. I don't think filereader works because it accesses the phone's file system and not the application's file system. Regardless, here's what I tried and it jumps to the error function when this line is called within gotFS:
fileSystem.root.getFile("version.txt", null, gotFileEntry, fail);
Here's my full index.html code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function test()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
document.write("gotFSreached");
fileSystem.root.getFile("version.txt", null, gotFileEntry, fail); // this jumps to fail
}
function gotFileEntry(fileEntry) {
document.write("gotFileEntryreached");
fileEntry.file(gotFile, fail);
}
function gotFile(file){
document.write("gotFilereached");
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
document.write(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
document.write("error");
}
</script>
<body>
<button type="button" onclick="test()">Print version.txt</button>
</body>
</html>
$.get("version.txt", function(data) {
// there u have version.txt data (in var data)
});
Using Phonegap1.9.0 Camera app for android. Followed the steps as per the phonegap documentation. But when I launch the app and click on Capture phone nothing happens.
When I look into the logcat navigator.camera.getPicture is undefined
Development version specified below.
Phonegap version:1.9.0
Eclipse: 3.7.2
Android: https://dl-ssl.google.com/android/eclipse/
AVD: 4.1
Device: Samsung GT-S5830, OS- Android 2.3.6
Can someone suggest me the steps to follow and the specific version that should be used to support the Camera.
HTML Code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height,
initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>PhoneGap WP7</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen"
title="no title" charset="utf-8" />
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="javascript.js"></script>
</head>
<body onLoad="setTimeout('delayer()', 5000)">
<h1>
VS Mag PhoneGap Photo Demo</h1>
<button onclick="capturePhoto();">Capture a Photo</button>
<br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Display from Library</button><br>
<img style="display: none; width: 200px; height: 200px;" alt="" id="capturedPhoto" src="" />
<img style="display: none; width: 200px; height: 200px;" alt="" id="selectedFromPhotoLibrary"
src="" />
</body>
</html>
Below is my JAVA SCRIPT 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 selectPhoto(useCamera)
{
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
if (useCamera)
{ // take picture
navigator.camera.getPicture(photoLoaded, onError, { allowEdit: true, destinationType: destinationType.FILE_URI });
}
else
{
// select from library
navigator.camera.getPicture(photoLoaded, onError, { allowEdit: true, sourceType: pictureSource.PHOTOLIBRARY, destinationType:
destinationType.FILE_URI });
}
}
//display image on the screen
function photoLoaded(imageData)
{
var temp_image=imageData;
document.getElementById("imageControl").src=temp_image;
}
// Called when a photo is successfully retrieved
function onPhotoDataSuccess(imageData) {
var capturedPhoto = document.getElementById('capturedPhoto');
capturedPhoto.style.display = 'block';
capturedPhoto.src = imageData;
navigator.notification.alert("Picture Successfully Captured!");
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
var selectedFromPhotoLibrary = document.getElementById('selectedFromPhotoLibrary');
selectedFromPhotoLibrary.style.display = 'block';
selectedFromPhotoLibrary.src = imageURI;
navigator.notification.alert("Picture Imported Captured!");
}
function capturePhoto() {
// Take picture using device camera and retrieve image
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}
// 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
});
}
// Error Handling
function onFail(message) {
alert('Failed because: ' + message);
}