File API
The PhoneGap File API gives you access to reading and writing to the local file system as well as functions to transfer files to and from a server.
Reading Device Directories
Create a new PhoneGap minimal project and copy the following function into your <script> section (adapted from the PhoneGap API page):
function getDirEntries() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
getReader(fileSystem.root);
//getDCIM(fileSystem.root);
}
function getDCIM(fileSystem) {
fileSystem.getDirectory("DCIM/Camera", null, getReader, console
.log("getDCIM fail"));
}
function getReader(dir) {
var directoryReader = dir.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(success, fail);
}
function success(entries) {
for (i = 0; i < entries.length; i++) {
if (entries[i].isFile) {
console.log("FILE:" + entries[i].name + ": "
+ entries[i].fullPath);
} else if (entries[i].isDirectory) {
console.log("DIR:" + entries[i].name + ": "
+ entries[i].fullPath);
} else {
console.log("UNKNOWN");
}
}
}
function fail(err) {
console.log("directoryReader error");
}
}
And this into your HTML body:
<button onclick="getDirEntries();">dir</button><br/>
Writing Files
Copy this into your <script> section:
function writeIt() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {
create : true,
exclusive : false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
text = document.getElementById('writeText').value;
// writer.onwriteend = function(evt) {
// console.log("contents of file now 'some sample text'");
// writer.truncate(11);
// writer.onwriteend = function(evt) {
// console.log("contents of file now 'some sample'");
// writer.seek(4);
// writer.write(" different text");
// writer.onwriteend = function(evt){
// console.log("contents of file now 'some different text'");
// }
// };
// };
writer.write(text);
writer.onwriteend = function(evt) {
alert("wrote: " + text);
}
}
function fail(error) {
console.log(error.code);
}
}
And this into your HTML body:
<input id="writeText" type="text" value="Enter text" style="width: 200px" />
<button onclick="writeIt();">write</button><br/>
Reading Files
Copy this into your <script> section:
function readIt() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file) {
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
document.getElementById('readText').innerHTML = evt.target.result;
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
}
And this into your HTML body:
<button onclick="readIt();">read</button>
<p id="readText">No Output</p>
HTML Forms
HTML forms are a simple way to collect data from the user and send it to a server.
Forms commonly specify:
- An action (often a link to a php file on a server)
- A method (commonly "get" or "post")
- Some inputs with type and name specified
- A submit input
HTTP Get Request
Let's take an example. This HTML creates a form that performs an HTTP Get request from my website:
<h2>GET Example</h2>
<form name="input"
action="http://produceconsumerobot.com/mobileweb2012/demos/form_example_get.php"
method="get">
first name: <input type="text" name="fname" />
last name: <input type="text" name="lname" />
<input type="submit" value="Submit" />
</form>
This form is submitting a get request with two variables, "fname" and "lname", to a php file when you hit submit
The php code that's processing that get request is here:
<?php
if (isset($_GET['fname'])){
$first = $_GET['fname'];
}else{
$first = "";
}
if (isset($_GET['lname'])){
$last = $_GET['lname'];
}else{
$last = "";
}
?>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<p>Hi
<?php
echo $first . " " . $last . "!";
?>
</p>
</body>
</html>
HTTP Post Request
Very similar is an post example.
<h2>POST Example</h2>
<form name="input"
action="http://produceconsumerobot.com/mobileweb2012/demos/form_example_post.php"
method="post">
first name: <input type="text" name="fname" />
last name: <input type="text" name="lname" />
<input type="submit" value="Submit" />
</form>
The php code that's processing that get request is here:
<?php
if (isset($_POST['fname'])){
$first = $_POST['fname'];
}else{
$first = "";
}
if (isset($_POST['lname'])){
$last = $_POST['lname'];
}else{
$last = "";
}
?>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<p>Hi
<?php
echo $first . " " . $last . "!";
?>
</p>
</body>
</html>
The principle difference between HTTP get and HTTP post whether the variables are passed as part of the address, e.g. http://produceconsumerobot.com/mobileweb2012/demos/form_example_get.php?fname=sean&lname=montgomery
or whether the variables are wrapped up in the body of the request.
Best practice also specifies that you should use HTTP post for operations that change the server, while using HTTP get for operations that are just "getting" information.
Uploading a file with an HTML Form
It's also possible to upload a file using an HTTP Form:
<h2>File Example</h2>
<form
action="http://produceconsumerobot.com/mobileweb2012/demos/upload_example.php"
method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file"
id="file" /> <br /> <input type="submit" name="submit"
value="Submit" />
</form>
And a server-side php script that receives the file:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("/home/smmontgom/produceconsumerobot.com/mobileweb2012/demos/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"/home/smmontgom/produceconsumerobot.com/mobileweb2012/demos/" . $_FILES["file"]["name"]);
echo "Stored in: " . "/home/smmontgom/produceconsumerobot.com/mobileweb2012/demos/" . $_FILES["file"]["name"];
}
}
?>
Downloading and Uploading Using PhoneGap File API
Download
To use Download in the PhoneGap API, first you'll want to install the latest PhoneGap because prior to 1.4.1 file download was not a supported feature.
- Go to: http://phonegap.com/ and download.
- Unzip the file and inside the android folder copy the phonegap-x.x.x.jx and phonegap-x.x.x.jar into the appropriate folders in your eclipse project.
- Delete the old .js and .jar files.
- Point your app at the new .js file in your HTML header.
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
- Point your app at the new .java file:
Go to: Project>Properties>Java Build Path>Libraries
and
click on "Add External JARs" and add the new file.
- Remove the old phonegap.jar from your Libraries list
Javascript:
function download() {
var fileTransfer = new FileTransfer();
fileTransfer.download(
'http://produceconsumerobot.com/mobileweb2012/demos/PARTY_PEOPLE.gif',
'/mnt/sdcard/PARTY_PEOPLE.gif',
function(entry) {
console.log("download complete: " + entry.fullPath);
}, function(error) {
console.log("download error source "
+ error.source);
console.log("download error target "
+ error.target);
console.log("upload error code" + error.code);
});
}
HTML:
<button onclick="download();">download</button><br />
Upload
Javascript:
function upload() {
var win = function(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
var fail = function(error) {
alert("An error has occurred: Code = " = error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = "readme" + Math.floor(Math.random() * 1000) + ".txt";
options.mimeType = "text/plain";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(
"/mnt/sdcard/readme.txt",
"http://produceconsumerobot.com/mobileweb2012/demos/upload_example.php",
win, fail, options);
}
HTML:
<button onclick="upload();">upload</button><br />
AJAX
AJAX stands for asynchronous Javascript and XML. AJAX lets you communicate with a server similar to HTML forms, but in an asynchronous way (using callback functions) without leaving the page you're currently on. This latter benefit is huge when using PhoneGap because you don't want to leave your PhoneGap API behind every time you post something to a server.
jQuery
jQuery is an amazing library, in general, but one of the nicest aspects is its AJAX interface. Using the jQuery AJAX interface is quite analagous to using HTML forms in that you can GET or POST. Furthermore you can send and receive JSON objects through the AJAX interface, making it very easy to upload form information to a server for later querying and populating lists or such in your app.
The below example simply uses HTTP post to send data to a php script on a server and then collects the returned data through the success callback.
Try copying this HTML into a new PhoneGap minimal project:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Minimal AppLaud App</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
var onDeviceReady = function() {
console.log("onDeviceReady()");
document.getElementById("devready").innerHTML = "OnDeviceReady fired.";
};
function init() {
console.log("init()");
document.addEventListener("deviceready", onDeviceReady, true);
}
var postSuccess = function(data) {
console.log(data.returnValue);
document.getElementById("serverReturn").innerHTML = data.returnValue;
}
var submitData = function() {
console.log("submitData()");
var s = document.getElementById("inputName").value;
console.log("submitting: " + s)
$.ajax({
type : 'POST',
url : 'http://produceconsumerobot.com/mobileweb2012/demos/ajaxpostdemo.php',
dataType : 'json',
data : {
sendValue : s
},
success : function(data) {
// sweet! we win!
postSuccess(data);
},
error : function(data) {
console.log("error");
// unpack the results to see what's going on
if (data) {
for (d in data) {
console.log(d + ": " + data[d]);
}
}
}
});
console.log("posted");
}
</script>
</head>
<body onLoad="init();" id="stage" class="theme">
<h2>Minimal AppLaud App</h2>
<p>Your app goes here.</p>
<p>
<span id="devready">onDeviceReady not fired.</span>
</p>
<label for="txtValue">Enter a name: </label>
<input type="text" name="txtValue" value="" id="inputName">
<button onClick="submitData();">Send</button>
<div id="serverReturn"></div>
</body>
</html>
And on the server we have the following php:
<?php
if (isset($_POST['sendValue'])){
$value = $_POST['sendValue'];
}else{
$value = "";
}
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>