Phonegap Bridge – File System and File Transfer

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

PHP Form and File Handling
PHP and the Web: Session : 4. Predefined variables PHP provides a large number of predefined global variables to any script which it runs also called.
More on Functions PHP mod 4 B. Simple Mail Transfer Protocol (SMTP) mail($to, $subject, $msg, $mailheaders); m08/8-1simple_form.html m08/8-1send_simpleform.php.
File System Interface CSCI 444/544 Operating Systems Fall 2008.
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Working With Data on Titanium Local Data Remote Data Titanium Data Options:
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
File Transfer Protocol CS-328 Dick Steflik. FTP RFC 959 uses two TCP Ports –one for control –one for data transfers command-response protocol control.
File System. NET+OS 6 File System Architecture Design Goals File System Layer Design Storage Services Layer Design RAM Services Layer Design Flash Services.
Sen Wang 11/17/2011.  RFC  “Form-based File Upload in HTML” NOV 1995 
Martin Kruliš by Martin Kruliš (v1.0)1.
Ajax (Asynchronous JavaScript and XML). AJAX  Enable asynchronous communication between a web client and a server.  A client is not blocked when an.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
Phonegap Bridge – Telephony CIS 136 Building Mobile Apps 1.
JavaScript, Fourth Edition
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Chapter 8 Cookies And Security JavaScript, Third Edition.
1 INFO 321 Server Technologies II FTP Material adapted from Dr. Randy Kaplan.
Christopher M. Pascucci Basic Structural Concepts of.NET Managing State & Scope.
Phonegap Bridge – Compass API CIS 136 Building Mobile Apps 1.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
Storing and Retrieving Data
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
15 – PHP(5) Informatics Department Parahyangan Catholic University.
Phonegap Bridge –Geolocation and Google maps CIS 136 Building Mobile Apps 1.
JQuery form submission CIS 136 Building Mobile Apps 1.
Phonegap Bridge – Storage CIS 136 Building Mobile Apps 1.
National College of Science & Information Technology.
Hypertext Transfer Protocol
Tiny http client and server
How HTTP Works Made by Manish Kushwaha.
Android Application Data Storage 1.
CSE 154 Lecture 11: AJAx.
HTTP – An overview.
Data Bridge Solving diverse data access in scientific applications
DBW - PHP DBW2017.
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
Hypertext Transport Protocol
CIS 136 Building Mobile Apps
OpenStorage API part II
Pre-assessment Questions
CIS 136 Building Mobile Apps
HTTP Protocol.
Implementing Cookies in PHP
IS333D: MULTI-TIER APPLICATION DEVELOPMENT
Testing REST IPA using POSTMAN
CSE 154 Lecture 11: AJAx.
WEB API.
File System and File Transfer
CSE 154 Lecture 22: AJAX.
CIS 136 Building Mobile Apps
<?php require("header.htm"); ?>
jQuery form submission
CIS 136 Building Mobile Apps
Phonegap Bridge Configuration file
18 File i/o, Parsing.
CIS 136 Building Mobile Apps
CIS 136 Building Mobile Apps
JavaScript & jQuery AJAX.
Deepak Shenoy Agni Software
Lecture 5: Functions and Parameters
The HTTP Protocol COSC 2206 Internet Tools The HTTP Protocol
PHP Forms and Databases.
HTTP Hypertext Transfer Protocol
PHP-II.
File Transfer Protocol
Presentation transcript:

Phonegap Bridge – File System and File Transfer CIS 136 Building Mobile Apps

File System Files API

Files API org.apache.cordova.file and org.apache.cordova.file-transfer Phonegap offers a sophisticated API to access and read files Can even download and upload files to a web sever Implements 2 different API’s Directories and System API File API The PhoneGap API provides a FileWriter class that allows you to write and save a file on the device The DirectoryEntry class provides a function to load the file to be written

FileSystem Object object representing information about the file system The name of the file system is unique across the list of exposed file systems The root property contains a DirectoryEntry object that represents the file system's root directory Properties name: The name of the file system. (DOMString) root: The root directory of the file system. (DirectoryEntry)

File System Objects DirectoryEntry DirectoryReader File FileEntry and FileError FileReader FileSystem FileTransfer and FileTransferError FileUploadOptions FileUploadresult FileWriter Flags LocalFileSystem MetaData

LocalFileSystem Object Defined on the Window object Provides a way to obtain root file systems Methods requestFileSystem(): Requests a filesystem resolveLocalFileSystemURI(): Retrieve a DirectoryEntry or FileEntry using local URI Constants LocalFileSystem.PERSISTENT: Used for storage that should not be removed by the user agent without application or user permission. LocalFileSystem.TEMPORARY: Used for storage with no guarantee of persistence

requestFileSystem() method LocalFileSystem Object Requests a file system in which to store application data Syntax: window.requestFileSystem(type, size, successFunc, errorFunc) window: reference to the global window object type: local file system type(Persistent or temporary) size: indicates how much storage space, in bytes, the application expects to need successFunc: passes a FileSystem object errorFunc: passes an error object

Directories

Directory Reader Object lists files and directories within a directory Methods readEntries: Read the entries in a directory

readEntries() methods DirectoryReader Object reads the entries in the directory Parameters: successCallback: A callback function that passes an array of FileEntry and DirectoryEntry objects. (Function) errorCallback: A callback function that executes if an error occurs when retrieving the directory listing. Passes a FileError object. Syntax: dirReader.readEntries(success,fail); success(ArrayOfFileEntries) { }

DirectoryEntry Object Represents a directory on a file system Properties isFile: Always false for a directory – always true for a file. (boolean) isDirectory: Always true for a directory – always false for a file. (boolean) name: The name of the DirectoryEntry, excluding the path leading to it. (DOMString) fullPath: The full absolute path from the root to the DirectoryEntry. (DOMString) filesystem: The file system on which the DirectoryEntry resides. (FileSystem) Methods getMetadata: Look up metadata about a directory. setMetadata: Set metadata on a directory. moveTo: Move a directory to a different location on the file system. copyTo: Copy a directory to a different location on the file system. toURL: Return a URL to help locate a directory. remove: Delete a directory. The directory must be empty. getParent: Look up the parent directory. createReader: Create a new DirectoryReader that can read entries from a directory. getDirectory: Create or look up a directory. getFile: Create or look up a file. removeRecursively: Delete a directory and all of its contents.

createReader() Directory Entry object creates a reader to read entries in the directory Syntax: var dirReader = filesys.root.createReader();

getFile() method (Directory Entry Object) Creates or looks up a file Parameters: path: The path to the file to be looked up or created. Either an absolute path, or a relative path from this DirectoryEntry. (DOMString) options: Options to specify whether the file is created if it doesn't exist. (Flags) successCallback: A callback that is passed a FileEntry object. (Function) errorCallback: A callback that executes if an error occurs when creating or looking up the file. Invoked with a FileError object. (Function) Example: entry.getFile("newFile.txt", {create: true, exclusive: false}, success, fail);

getMetaData() method DirectoryEntry Object Looks up metadata about a directory Methods successCallback: A callback function to execute with a Metadata object. (Function) errorCallback: A callback function to execute if an error occurs when retrieving the Metadata. Passes a FileError object. (Function) Syntax: entry.getMetadata(success, fail);

Remove() method Directory Entry Object Deletes a directory. An error results if the app attempts to: delete a directory that is not empty delete the root directory of a filesystem Parameters: successCallback: A callback that executes after the directory is deleted. No parameters. errorCallback: A callback that executes if an error occurs when attempting to delete the directory. Passed a FileError object.

Files

FileReader Object Allows basic access to a file offers a way to read files from the device's file system Methods abort: Aborts reading file. readAsDataURL: Read file and return data as a base64- encoded data URL. readAsText: Reads text file. readAsBinaryString: Reads file as binary and returns a binary string. readAsArrayBuffer: Reads file as an ArrayBuffer.

FileEntry Object Represents a file on a file system Properties Methods isFile: Always true. (boolean) isDirectory: Always false. (boolean) name: The name of the FileEntry, excluding the path leading to it. (DOMString) fullPath: The full absolute path from the root to the FileEntry. (DOMString) filesystem: The file system on which the FileEntry resides. (FileSystem) Methods getMetadata: Look up metadata about a file. setMetadata: Set metadata on a file. moveTo: Move a file to a different location on the file system. copyTo: Copy a file to a different location on the file system. toURL: Return a URL that can be used to locate a file. remove: Delete a file. getParent: Look up the parent directory. createWriter: Creates a FileWriter object that can be used to write to a file. file: Creates a File object containing file properties.

createWriter() method FileEntry Object Create a FileWriter object Parameters: successCallback: A callback that is passed a FileWriter object. (Function) errorCallback: A callback that executes if an error occurs while attempting to create the FileWriter. Invoked with a FileError object. (Function) Syntax: entry.createWriter(success, fail);

createWriter() method FileEntry Object Properties readyState: One of the three possible states, either INIT, WRITING, or DONE. fileName: The name of the file to be written. (DOMString) length: The length of the file to be written. (long) position: The current position of the file pointer. (long) error: An object containing errors. (FileError) onwritestart: Called when the write starts. (Function) onwrite: Called when the request has completed successfully. (Function) onabort: Called when the write has been aborted. For instance, by invoking the abort() method. (Function) onerror: Called when the write has failed. (Function) onwriteend: Called when the request has completed (either in success or failure). (Function)

createWriter() method FileEntry Object Methods abort: Aborts writing the file. seek: Moves the file pointer to the specified byte. truncate: Shortens the file to the specified length. write: Writes data to the file.

file() method File Entry Object Return a File object that represents the current state of the file Parameters: successCallback: A callback that is passed a File object. (Function) errorCallback: A callback that executes if an error occurs when creating the File object, such as when the file no longer exists. Passed a FileError object. (Function

File Transfer Files API

File Transfer API org.apache.cordova.file-transfer version 0.4.6 allows you to upload and download files Protocol used: HTTP multi-part POST request

File Transfer Object Properties Methods: onprogress: Called with a ProgressEvent whenever a new chunk of data is transferred. (Function) Methods: upload: sends a file to a server download: downloads a file from server abort: Aborts an in-progress transfer

Upload

Upload() method upload(URL, server, success, fail, options,trust); fileURL: Filesystem URL representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device. server: URL of the server to receive the file, as encoded by encodeURI() . successCallback: A callback that is passed a Metadata object. (Function) errorCallback: A callback that executes if an error occurs retrieving the Metadata . Invoked with a FileTransferError object. (Function) options: Optional parameters (Object). Valid keys: fileKey: The name of the form element. Defaults to file . (DOMString) fileName: The file name to use when saving the file on the server. Defaults to image.jpg . (DOMString) mimeType: The mime type of the data to upload. Defaults to image/jpeg . (DOMString) params: A set of optional key/value pairs to pass in the HTTP request. (Object) chunkedMode: Whether to upload the data in chunked streaming mode. Defaults to true . (Boolean) headers: A map of header name/header values. Use an array to specify more than one value. (Object) trustAllHosts: Optional parameter, defaults to false . If set to true , it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use.

Example Assumes variable fileURL contains a valid URL to a text file on the device, for example, cdvfile://localhost/persistent/path/to/file.txt var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); options.mimeType = "text/plain"; var params = {}; params.value1 = "test"; params.value2 = "param"; options.params = params; var server=‘encodeURI("http://some.server.com/upload.php")’; var ftObj = new FileTransfer(); ftObj.upload(fileURL,server, success, fail, options);

Example (cont.) Success callback will receive a FileUploadResult object with the following properties: bytesSent: The number of bytes sent to the server as part of the upload. (long) responseCode: The HTTP response code returned by the server. (long) response: The HTTP response returned by the server. (DOMString) headers: The HTTP response headers by the server. (Object) function success(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent ); } function fail(error) { alert("An error has occurred: Code = " + error.code); console.log("upload error source " + error.source); console.log(“ upload error target " + error.target );

Download

download() method download(server, fileURL, success, fail,trust,options); fileURL: Filesystem URL representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device server: URL of the server to receive the file, as encoded by encodeURI() successCallback: A callback that is passed a FileEntry object. (Function) errorCallback: A callback that executes if an error occurs retrieving the Metadata . Invoked with a FileTransferError object. (Function) options: Optional parameters (Object) headers: A map of header name/header values. Use an array to specify more than one value. (Object) trustAllHosts: Optional parameter, defaults to false . If set to true , it accepts all security certificates. This is useful since Android rejects self- signed security certificates.

Example Assumes variable fileURL contains a valid URL to a text file on the device, for example, cdvfile://localhost/persistent/path/to/file.txt var fileTransfer = new FileTransfer(); var server = encodeURI("http://some.server.com/download.php"); var options = ‘headers: { "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="}’ fileTransfer.download(server, fileURL, success, fail, false, options); function success(entry) { console.log("download complete: " + entry.toURL()); } function fail (error) { console.log("download error source " + error.source); console.log("download error target " + error.target); console.log("upload error code" + error.code);

Abort

Abort Aborts an in-progress transfer The onerror callback is passed a FileTransferError object has an error code of FileTransferError.ABORT_ERR (4)

FileTransferError Object A FileTransferError object is passed to an error callback when an error occurs. Properties code: One of the predefined error codes listed below. (Number) source: URL to the source. (String) target: URL to the target. (String) http_status: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number) exception: Either e.getMessage or e.toString (String) Constants 1 = FileTransferError.FILE_NOT_FOUND_ERR 2 = FileTransferError.INVALID_URL_ERR 3 = FileTransferError.CONNECTION_ERR 4 = FileTransferError.ABORT_ERR 5 = FileTransferError.NOT_MODIFIED_ERR

Example Assumes variable fileURL contains a valid URL to a text file on the device, for example, cdvfile://localhost/persistent/path/to/file.txt var options = new FileUploadOptions(); options.fileKey="file"; options.fileName="myphoto.jpg"; options.mimeType="image/jpeg"; Var server = ‘encodeURI("http://some.server.com/upload.php"), ’ var ftObj = new FileTransfer(); ftObj.upload(fileURL, server, success, fail, options); ftObj.abort(); function success(r) { console.log("Should not be called."); } function fail(error) { // error.code == FileTransferError.ABORT_ERR alert("An error has occurred: Code = " + error.code); console.log("upload error source " + error.source); console.log("upload error target " + error.target);