File

File

This API is based on the W3C File API. An API to read, write and navigate file system hierarchies.

Objects

Permissions

Android

app/res/xml/plugins.xml

<plugin name="File" value="org.apache.cordova.FileUtils" />
<plugin name="FileTransfer" value="org.apache.cordova.FileTransfer" />

app/AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Bada

No permissions are required.

BlackBerry WebWorks

www/plugins.xml

<plugin name="File" value="org.apache.cordova.file.FileManager" />
<plugin name="FileTransfer" value="org.apache.cordova.http.FileTransfer" />

www/config.xml

<feature id="blackberry.io.file" required="true" version="1.0.0.0" />
<feature id="blackberry.utils"   required="true" version="1.0.0.0" />
<feature id="blackberry.io.dir"  required="true" version="1.0.0.0" />
<rim:permissions>
    <rim:permit>access_shared</rim:permit>
</rim:permissions>

iOS

App/Supporting Files/Cordova.plist

<key>Plugins</key>
<dict>
    <key>File</key>
    <string>CDVFile</string>
</dict>

<key>Plugins</key>
<dict>
    <key>FileTransfer</key>
    <string>CDVFileTransfer</string>
</dict>

webOS

No permissions are required.

Windows Phone

No permissions are required.

File

This object contains attributes of a single file.

Properties

Details

The File object contains attributes of a single file. You can get an instance of a File object by calling the file method of a FileEntry object.

Supported Platforms


FileReader

FileReader is an object that allows one to read a file.

Properties

Methods

Details

The FileReader object is a way to read files from the devices file system. Files can be read as text or as a base64 data encoded string. Users register their own event listners to receive the loadstart, progress, load, loadend, error and abort events.

Supported Platforms

Read As Data URL

Parameters: - file - the file object to read

Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsDataURL(file);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.file(win, fail);

Read As Text

Parameters:

Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.file(win, fail);

Abort Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
    reader.abort();
};

function fail(error) {
    console.log(error.code);
}

entry.file(win, fail);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>FileReader Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // Cordova is ready
    //
    function onDeviceReady() {
        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);
        };
        reader.readAsText(file);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Read File</p>
  </body>
</html>

iOS Quirks


FileWriter

FileWriter is an object that allows one to write a file.

Properties

Methods

Details

The FileWriter object is a way to write files to the device file system (UTF-8 encoded). Users register their own event listeners to receive the writestart, progress, write, writeend, error and abort events.

A FileWriter is created for a single file. You can use it to write to a file multiple times. The FileWriter maintains the file's position and length attributes, so you can seek and write anywhere in the file. By default, the FileWriter writes to the beginning of the file (will overwrite existing data). Set the optional append boolean to true in the FileWriter's constructor to begin writing to the end of the file.

Supported Platforms

Seek Quick Example

function win(writer) {
    // fast forwards file pointer to end of file
    writer.seek(writer.length); 
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Truncate Quick Example

function win(writer) {
    writer.truncate(10);    
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Write Quick Example

function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.write("some sample text");
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Append Quick Example

function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.seek(writer.length);
    writer.write("appended text");
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Abort Quick Example

function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.write("some sample text");
    writer.abort();
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>FileWriter Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        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) {
        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("some sample text");
    }

    function fail(error) {
        console.log(error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Write File</p>
  </body>
</html>

FileSystem

This object represents a file system.

Properties

Details

The FileSystem object represents information about the file system. The name of the file system will be unique across the list of exposed file systems. The root property contains a DirectoryEntry object which represents the root directory of the file system.

Supported Platforms

File System Quick Example

function onSuccess(fileSystem) {
    console.log(fileSystem.name);
    console.log(fileSystem.root.name);
}

// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>File System Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
    }

    function onFileSystemSuccess(fileSystem) {
        console.log(fileSystem.name);
        console.log(fileSystem.root.name);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>File System</p>
  </body>
</html>

FileEntry

This object represents a file on a file system. It is defined in the W3C Directories and Systems specification.

Properties

NOTE: The following attributes are defined by the W3C specification, but are not supported by Cordova:

Methods

Supported Platforms

getMetadata

Look up metadata about a file.

Parameters:

Quick Example

function success(metadata) {
    console.log("Last Modified: " + metadata.modificationTime);
}

function fail(error) {
    alert(error.code);
}

// Request the metadata object for this entry
entry.getMetadata(success, fail);

setMetadata

Set metadata on a file. Only works on iOS currently - this will set the extended attributes of a file.

Parameters:

Quick Example

function success() {
    console.log("The metadata was successfully set.");
}

function fail() {
    alert("There was an error in setting the metadata");
}

// Set the metadata
entry.setMetadata(success, fail, { "com.apple.MobileBackup": 1});

iOS Quirk

moveTo

Move a file to a different location on the file system. It is an error to attempt to:

In addition, an attempt to move a file on top of an existing file must attempt to delete and replace that file.

Parameters:

Quick Example

function success(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function moveFile(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        parentEntry = new DirectoryEntry(parentName, parent);

    // move the file to a new directory and rename it
    entry.moveTo(parentEntry, "newFile.txt", success, fail);
}

copyTo

Copy a file to a new location on the file system. It is an error to attempt to:

Parameters:

Quick Example

function win(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function copyFile(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        parentEntry = new DirectoryEntry(parentName, parent);

    // copy the file to a new directory and rename it
    entry.copyTo(parentEntry, "file.copy", success, fail);
}

toURL

Returns a URL that can be used to locate the file.

Quick Example

// Request the URL for this entry
var fileURL = entry.toURL();
console.log(fileURL);

remove

Deletes a file.

Parameters:

Quick Example

function success(entry) {
    console.log("Removal succeeded");
}

function fail(error) {
    alert('Error removing file: ' + error.code);
}

// remove the file
entry.remove(success, fail);

getParent

Look up the parent DirectoryEntry containing the file.

Parameters:

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert(error.code);
}

// Get the parent DirectoryEntry
entry.getParent(success, fail);

createWriter

Create a FileWriter object associated with the file that the FileEntry represents.

Parameters:

Quick Example

function success(writer) {
    writer.write("Some text to the file");
}

function fail(error) {
    alert(error.code);
}

// create a FileWriter to write to the file
entry.createWriter(success, fail);

file

Return a File object that represents the current state of the file that this FileEntry represents.

Parameters:

Quick Example

function success(file) {
    console.log("File size: " + file.size);
}

function fail(error) {
    alert("Unable to retrieve file properties: " + error.code);
}

// obtain properties of a file
entry.file(success, fail);

DirectoryEntry

This object represents a directory on a file system. It is defined in the W3C Directories and Systems specification.

Properties

NOTE: The following attributes are defined by the W3C specification, but are not supported by Cordova:

Methods

The following methods can be invoked on a DirectoryEntry object:

Supported Platforms

getMetadata

Look up metadata about a directory.

Parameters:

Quick Example

function success(metadata) {
    console.log("Last Modified: " + metadata.modificationTime);
}

function fail(error) {
    alert(error.code);
}

// Request the metadata object for this entry
entry.getMetadata(success, fail);

setMetadata

Set metadata on a directory. Only works on iOS currently - this will set the extended attributes of a directory.

Parameters:

Quick Example

function success() {
    console.log("The metadata was successfully set.");
}

function fail() {
    alert("There was an error in setting the metadata");
}

// Set the metadata
entry.setMetadata(success, fail, { "com.apple.MobileBackup": 1});

iOS Quirk

moveTo

Move a directory to a different location on the file system. It is an error to attempt to:

In addition, an attempt to move a directory on top of an existing empty directory must attempt to delete and replace that directory.

Parameters:

Quick Example

function success(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function moveDir(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        newName = document.getElementById('newName').value,
        parentEntry = new DirectoryEntry(parentName, parent);

    // move the directory to a new directory and rename it
    entry.moveTo(parentEntry, newName, success, fail);
}

copyTo

Copy a directory to a different location on the file system. It is an error to attempt to:

Directory copies are always recursive - that is, they copy all contents of the directory.

Parameters:

Quick Example

function win(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function copyDir(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        newName = document.getElementById('newName').value,
        parentEntry = new DirectoryEntry(parentName, parent);

    // copy the directory to a new directory and rename it
    entry.copyTo(parentEntry, newName, success, fail);
}

toURL

Returns a URL that can be used to locate the directory.

Quick Example

// Get the URL for this directory
var dirURL = entry.toURL();
console.log(dirURL);

remove

Deletes a directory. It is an error to attempt to:

Parameters:

Quick Example

function success(entry) {
    console.log("Removal succeeded");
}

function fail(error) {
    alert('Error removing directory: ' + error.code);
}

// remove this directory
entry.remove(success, fail);

getParent

Look up the parent DirectoryEntry containing the directory.

Parameters:

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert('Failed to get parent directory: ' + error.code);
}

// Get the parent DirectoryEntry
entry.getParent(success, fail);

createReader

Creates a new DirectoryReader to read entries in a directory.

Quick Example

// create a directory reader
var directoryReader = entry.createReader();

getDirectory

Creates or looks up an existing directory. It is an error to attempt to:

Parameters:

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert("Unable to create new directory: " + error.code);
}

// Retrieve an existing directory, or create it if it does not already exist
entry.getDirectory("newDir", {create: true, exclusive: false}, success, fail);

getFile

Creates or looks up a file. It is an error to attempt to:

Parameters:

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert("Failed to retrieve file: " + error.code);
}

// Retrieve an existing file, or create it if it does not exist
entry.getFile("newFile.txt", {create: true, exclusive: false}, success, fail);

removeRecursively

Deletes a directory and all of its contents. In the event of an error (e.g. trying to delete a directory that contains a file that cannot be removed), some of the contents of the directory may be deleted. It is an error to attempt to:

Parameters:

Quick Example

function success(parent) {
    console.log("Remove Recursively Succeeded");
}

function fail(error) {
    alert("Failed to remove directory or it's contents: " + error.code);
}

// remove the directory and all it's contents
entry.removeRecursively(success, fail);

DirectoryReader

An object that lists files and directories in a directory. Defined in the Directories and Systems specification.

Methods

Supported Platforms

readEntries

Read the entries in this directory.

Parameters:

Quick Example

function success(entries) {
    var i;
    for (i=0; i<entries.length; i++) {
        console.log(entries[i].name);
    }
}

function fail(error) {
    alert("Failed to list directory contents: " + error.code);
}

// Get a directory reader
var directoryReader = dirEntry.createReader();

// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);

FileTransfer

FileTransfer is an object that allows you to upload files to a server or download files from a server.

Properties

N/A

Methods

Details

The FileTransfer object provides a way to upload files to a remote server using an HTTP multi-part POST request. Both HTTP and HTTPS protocols are supported. Optional parameters can be specified by passing a FileUploadOptions object to the upload method. On successful upload, the success callback will be called with a FileUploadResult object. If an error occurs, the error callback will be invoked with a FileTransferError object. It is also possible to download a file from remote and save it on the device (only iOS and Android).

Supported Platforms

upload

Parameters:

Quick Example

// !! Assumes variable fileURI contains a valid URI to a  text file on the device

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=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var params = new Object();
params.value1 = "test";
params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURI, "http://some.server.com/upload.php", win, fail, options);

Full Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>File Transfer Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
    <script type="text/javascript" charset="utf-8">

        // Wait for Cordova to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready
        //
        function onDeviceReady() {

            // 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;

            var ft = new FileTransfer();
            ft.upload(imageURI, "http://some.server.com/upload.php", win, fail, options);
        }

        function win(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);
        }

        </script>
</head>
<body>
    <h1>Example</h1>
    <p>Upload File</p>
</body>
</html>

iOS Quirks

Setting headers for FileTransfer Upload:

Quick Example

function win(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);
}

var uri = "http://some.server.com/upload.php";

var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var params = new Object();
params.headers={'headerParam':'headerValue'};

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURI, uri, win, fail, options);

download

Parameters:

Quick Example

 // !! Assumes variable url contains a valid URI to a file on a server and filePath is a valid path on the device

var fileTransfer = new FileTransfer();

fileTransfer.download(
    url,
    filePath,
    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);
    }
);

FileUploadOptions

A FileUploadOptions object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.

Properties

Description

A FileUploadOptions object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.

iOS Quirk

WP7 Quirk


FileUploadResult

A FileUploadResult object is returned via the success callback of the FileTransfer upload method.

Properties

Description

The FileUploadResult object is returned via the success callback of the FileTransfer upload method.

iOS Quirks


Flags

This object is used to supply arguments to the DirectoryEntry getFile and getDirectory methods, which look up or create files and directories, respectively.

Properties

Supported Platforms

Quick Example

// Get the data directory, creating it if it doesn't exist.
dataDir = fileSystem.root.getDirectory("data", {create: true});

// Create the lock file, if and only if it doesn't exist.
lockFile = dataDir.getFile("lockfile.txt", {create: true, exclusive: true});

LocalFileSystem

This object provides a way to obtain root file systems.

Methods

Constants

Details

The LocalFileSystem object methods are defined on the window object.

Supported Platforms

Request File System Quick Example

function onSuccess(fileSystem) {
    console.log(fileSystem.name);
}

// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);

Resolve Local File System URI Quick Example

function onSuccess(fileEntry) {
    console.log(fileEntry.name);
}

window.resolveLocalFileSystemURI("file:///example.txt", onSuccess, onError);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>Local File System Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
        window.resolveLocalFileSystemURI("file:///example.txt", onResolveSuccess, fail);
    }

    function onFileSystemSuccess(fileSystem) {
        console.log(fileSystem.name);
    }

    function onResolveSuccess(fileEntry) {
        console.log(fileEntry.name);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Local File System</p>
  </body>
</html>

Metadata

This interface supplies information about the state of a file or directory.

Properties

Details

The Metadata object represents information about the state of a file or directory. You can get an instance of a Metadata object by calling the getMetadata method of a DirectoryEntry or FileEntry object.

Supported Platforms

Quick Example

function win(metadata) {
    console.log("Last Modified: " + metadata.modificationTime);
}

// Request the metadata object for this entry
entry.getMetadata(win, null);

FileError

A 'FileError' object is set when an error occurs in any of the File API methods.

Properties

Constants

Description

The FileError object is the only parameter of any of the File API's error callbacks. Developers must read the code property to determine the type of error.


FileTransferError

A FileTransferError object is returned via the error callback when an error occurs.

Properties

Constants

Description

The FileTransferError object is returned via the error callback when an error occurs when uploading or downloading a file.