Download presentation
Presentation is loading. Please wait.
1
File System and File Transfer
CIS 136 Building Mobile Apps
2
File System Files Plug-In
3
File System Plug-In Implemented by Google Chrome and used in cordova for file manipulation Allows read/write access to files residing on the device using the following functions: Directories (folders): DirectoryEntry, LocalFileSystem objects Reading and manipulating files: FileList, FileReader methods Creating and writing: FileWriter method Directories and file system access: DirectoryEntry, LocalFileSystem objects Transfers files (upload/download to/from a web server)
4
requestFileSystem() method
Gets access to the file system for either persistent or temporary storage access is granted for the sandboxed file system only If calling the first time, new storage is created for the app – the app cannot access another app's files, therefore the app cannot read/write files to an arbitrary folder on the hard drive For external access, use window.resolveLocalFileSystemURL() Syntax: window.requestFileSystem(type, size, successFunc, errorFunc) window: reference to the global window object type: local file system type(LocalFileSystem.PERSISTENT or LocalFileSystem.TEMPORARY) size: indicates how much storage space, in bytes, the application expects to need successFunc: returns a FileSystem object errorFunc: passes an error object
5
FileSystem Object object representing information about the file system (fs) with the following properties: name: The name of the file system (fs.name) root: a FileSystem object (fs.root)that contains a DirectoryEntry interface to read or create directories FileEntry interface to read or create files
6
Directories (folders)
FileSystem objects’ DirectoryEntry interface to manage directories
7
(fs.root) DirectoryEntry interface: getDirectory() Method
used to read or create directories, and if successful, provides a directoryEntry object with properties: isDirectory: Always true for a directory name: The name of the DirectoryEntry, excluding the path leading to it (string) fullPath: The full absolute path from the root to the DirectoryEntry (string). filesystem: The file system on which the DirectoryEntry resides. (object) Syntax: fs.root.getDirectory(name,options, successFunc, errorFunc)l window.requestFileSystem(window.TEMPORARY, 1024*1024, onSuccess, onError) function onSuccess(fs) { fs.root.getDirectory('MyPictures', {create: true}, onSuccess, onError); } function onSuccess(dirEntry) { // create subfolder strDirName = dirEntry.fullPath; document.geteELementById(“mainFolderName”).innerHTML = “main folder name is: “ + strDirName); dirEntry.getDirectory(‘Vacation’,{create:true},onSubSuccess,onSubError); function onSubSuccess(dirEntry) document.geteELementById(“subFolderName”).innerHTML = “sub folder name is: “ + strDirName);
8
(fs.root) DirectoryEntry interface: readEntries() methods
reads the contents of a directory Syntax: window.requestFileSystem(window.TEMPORARY, 1024*1024, onSuccess, onError) function onSuccess(fs) { var dirReader = fs.root.createReader('MyPictures', {create: true}, onSuccess, onError); } function onSuccess(dirEntries) { dirReader.readEntries(success,fail); } function success(ArrayOfFileEntries) { // code goes here
9
FileSystem objects’ FileEntry interface to manage files
10
(fs.root) FileEntry interface: getFile() method
Creates or looks up a persistent file window.requestFileSystem(LocalFileSystem.PERSISTENT,0, onSuccess, onError) function onSuccess(fs) { fs.root.getFile(‘myFile.txt', {create: true}, onFSSuccess, onFSError); } function onFSSuccess(fileEntry) { var strFullPath = fileEntry.fullPath;
11
(fs.root) FileEntry interface: getFile() method
Creates or looks up a temporary file Temporary storage may be deleted by the operating system if the device runs low on memory window.requestFileSystem(window.TEMPORARY,5*1024*1024, onSuccess, onError) function onSuccess(fs) { fs.root.getFile(‘myFile.txt', {create: true}, onFSSuccess, onFSError); } function onFSSuccess(fileEntry) { var strFullPath = fileEntry.fullPath;
12
(fs.root) FileEntry interface: writeFile() method
Writes content to a file var dataObj= new Blob(['some text'], { type: 'text/plain' }); window.requestFileSystem(window.TEMPORARY,5*1024*1024, onSuccess, onError) function onSuccess(fs) { fs.root.getFile(‘myFile.txt', {create: true}, onFSSuccess, onFSError); } function onFSSuccess(fileEntry) { fileEntry.createWriter(function(fileWriter) fileWriter.onwriteend = function() { console.log("Successful file write..."); }; fileWriter.onwriteerror = function(err) { console.log(“write failed...“ + err.ToString()); fileWriter.write(dataObj);
13
(fs.root) FileEntry interface: readFile() method
Reads existing file var dataObj=“some text”; window.requestFileSystem(window.TEMPORARY,5*1024*1024, onSuccess, onError) function onSuccess(fs) { fs.root.getFile(‘myFile.txt', {create: true}, onFSSuccess, onFSError); } function onFSSuccess(fileEntry) { fileEntry.file(function(file) var reader = new FileReader(); reader.onloadend = function() document.getElementById(“output”).innerHTML = fileEntry.fullPath + “:” + this.reult); reader.readAsText(file);
14
(fs.root) FileEntry interface: appendFile() method
window.resolveLocalFileSystemURL. In this example, pass the cross-platform Cordova file URL, cordova.file.dataDirectory, to the function. The success callback receives a DirectoryEntry object, which you can use to do things like create a filevar dataObj=“some text”; window.resolveLocalFileSystem(cordova.file.dataDirectory, onSuccess, onError) function onSuccess(dirEntry) { //dirEntry is fs.root console.log(dirEntry.name); var isAppend = true; createFile(dirEntry, "fileToAppend.txt", isAppend); dirEntry.getFile(‘myFile.txt', isAppend, function(fileEntry) { fileEntry.createWriter(function (fileWriter) { fileWrite.write(dataObj); }); });
15
Error codes
16
File Transfer Files API
17
File Transfer Object Allows you to upload and download files
Protocol used: HTTP multi-part POST request Properties 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
18
Upload
19
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.
20
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);
21
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 );
22
Download
23
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.
24
Example Assumes variable fileURL contains a valid URL to a text file on the device, for example, DCIM/0/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);
25
Abort
26
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
27
Example – forced abort 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(); //stops an in process transfer 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);
28
Resources https://www.html5rocks.com/en/tutorials/file/filesystem
file/index.html#persistent
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.