Download presentation
Presentation is loading. Please wait.
1
Phonegap Bridge – File System and File Transfer
CIS 136 Building Mobile Apps
2
File System Files API
3
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
4
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)
5
File System Objects DirectoryEntry DirectoryReader File
FileEntry and FileError FileReader FileSystem FileTransfer and FileTransferError FileUploadOptions FileUploadresult FileWriter Flags LocalFileSystem MetaData
6
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
7
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
8
Directories
9
Directory Reader Object
lists files and directories within a directory Methods readEntries: Read the entries in a directory
10
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) { }
11
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.
12
createReader() Directory Entry object
creates a reader to read entries in the directory Syntax: var dirReader = filesys.root.createReader();
13
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);
14
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);
15
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.
16
Files
17
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.
18
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.
19
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);
20
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)
21
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.
22
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
23
File Transfer Files API
24
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
25
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
26
Upload
27
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.
28
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(" var ftObj = new FileTransfer(); ftObj.upload(fileURL,server, success, fail, options);
29
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 );
30
Download
31
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.
32
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(" 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);
33
Abort
34
Abort Aborts an in-progress transfer
The onerror callback is passed a FileTransferError object has an error code of FileTransferError.ABORT_ERR (4)
35
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
36
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(" ’ 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);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.