File
The
FileReader
andFileWriter
objects provide access to the devices file system for reading of files.
Objects
FileReader
FileReader is an object that allows one to read a file.
Properties
- readyState: One of the three states the reader can be in EMPTY, LOADING or DONE.
- result: The contents of the file that has been read. (DOMString)
- error: An object containing errors. (FileError)
- onloadstart: Called when the read starts. . (Function)
- onprogress: Called while reading the file, reports progress (progess.loaded/progress.total). (Function) -NOT SUPPORTED
- onload: Called when the read has successfully completed. (Function)
- onabort: Called when the read has been aborted. For instance, by invoking the abort() method. (Function)
- onerror: Called when the read has failed. (Function)
- onloadend: Called when the request has completed (either in success or failure). (Function)
Methods
- abort: Aborts reading file.
- readAsDataURL: Read file and return data as a base64 encoded data url.
- readAsText: Reads text file.
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
- Android
- BlackBerry WebWorks (OS 5.0 and higher)
- iOS
Read As Data URL
Parameters: - fileName - the full path of the file to read
Quick Example
var win = function(evt) {
console.log(evt.target.result);
};
var fail = function(evt) {
console.log(evt.target.error.code);
};
var paths = navigator.fileMgr.getRootPaths();
var reader = new FileReader();
reader.onload = win;
reader.onerror= fail;
reader.readAsDataURL(paths[0] + "readme.txt");
Read As Text
Parameters:
- fileName - the full path of the file to read
- encoding - the encoding to use to encode the file's content. Default is UTF8.
Quick Example
var win = function(evt) {
console.log(evt.target.result);
};
var fail = function(evt) {
console.log(evt.target.error.code);
};
var paths = navigator.fileMgr.getRootPaths();
var reader = new FileReader();
reader.onload = win;
reader.onerror= fail;
reader.readAsText(paths[0] + "readme.txt");
Abort Quick Example
var aborted = function(evt) {
console.log(evt.target.error.code);
};
var paths = navigator.fileMgr.getRootPaths();
var reader = new FileReader();
reader.onabort = aborted;
reader.readAsText(paths[0] + "readme.txt");
reader.abort();
Full Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
var paths = navigator.fileMgr.getRootPaths();
var reader = new FileReader();
reader.onload = win;
reader.onerror= fail;
reader.readAsText(paths[0] + "readme.txt");
}
function win(evt) {
console.log(evt.target.result);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body onload="onLoad()">
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
iOS Quirks
- encoding parameter is not supported, UTF8 encoding is always used.
- readAsDataUrl() is not supported.
FileWriter
FileWriter is an object that allows one to write a file.
Properties
- readyState: One of the three states the reader can be in 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)
- onprogress: Called while writing the file, reports progress (progess.loaded/progress.total). (Function) -NOT SUPPORTED
- 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)
Methods
- abort: Aborts writing file.
- seek: Moves the file pointer to the byte specified.
- truncate: Shortens the file to the length specified.
- write: Writes data to the file.
Details
The FileWriter
object is a way to write files from the devices file system. 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
- Android
- BlackBerry WebWorks (OS 5.0 and higher)
- iOS
Seek Quick Example
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
// fast forwards file pointer to end of file
writer.seek(writer.length);
Truncate Quick Example
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.truncate(10);
Write Quick Example
var writeSuccess = function(evt) {
console.log("Write has succeeded");
};
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.onwrite = writeSuccess;
writer.write("some sample text");
Append Quick Example
var writeSuccess = function(evt) {
console.log("Write has succeeded");
};
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt", true);
writer.onwrite = writeSuccess;
writer.write("some more text");
Abort Quick Example
var aborted = function(evt) {
console.log(evt.target.error);
};
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.onabort = aborted;
writer.write("some sample text");
writer.abort();
Full Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.onwrite = writeSuccess;
writer.write("some sample text");
// The file is now 'some sample text'
}
function writeSuccess() {
console.log("Write has succeeded");
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.seek(4);
writer.truncate(writer.position);
// The file is now 'some'
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body onload="onLoad()">
<h1>Example</h1>
<p>Write File</p>
</body>
</html>
FileTransfer
FileTransfer is an object that allows you to upload files to a server.
Properties
N/A
Methods
- upload: sends a file to a server.
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.
Supported Platforms
- Android
- BlackBerry WebWorks (OS 5.0 and higher)
Quick Example
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);
}
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="newfile.txt";
options.mimeType="text/plain";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var paths = navigator.fileMgr.getRootPaths();
var ft = new FileTransfer();
ft.upload(paths[0] + "newfile.txt", "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>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="newfile.txt";
options.mimeType="text/plain";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var paths = navigator.fileMgr.getRootPaths();
var ft = new FileTransfer();
ft.upload(paths[0] + "newfile.txt", "http://some.server.com/upload.php", win, fail, options);
}
function win(evt) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(evt) {
alert("An error has occurred: Code = " = error.code);
}
</script>
</head>
<body onload="onLoad()">
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
FileUploadOptions
A FileUploadOptions
object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.
Properties
- fileKey: The name of the form element. If not set defaults to "file". (DOMString)
- fileName: The file name you want the file to be saved as on the server. If not set defaults to "image.jpg". (DOMString)
- mimeType: The mime type of the data you are uploading. If not set defaults to "image/jpeg". (DOMString)
- params: A set of optional key/value pairs to be passed along in the HTTP request. (Object)
Description
A FileUploadOptions
object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.
FileUploadResult
A FileUploadResult
object is returned via the success callback of the FileTransfer upload method.
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)
Description
The FileUploadResult
object is returned via the success callback of the FileTransfer upload method.
FileError
A 'FileError' object is set on the FileWriter/FileReader error property when an error occurs.
Properties
- code: One of the predefined error codes listed below.
Constants
FileError.NOT_FOUND_ERR
FileError.SECURITY_ERR
FileError.ABORT_ERR
FileError.NOT_READABLE_ERR
FileError.ENCODING_ERR
FileError.NO_MODIFICATION_ALLOWED_ERR
FileError.INVALID_STATE_ERR
FileError.SYNTAX_ERR
Description
The FileError
object may be thrown when an unrecoverable error occurs when reading, writing, seeking or truncating a file. When the user calls the abort method of the writer a FileError with a code of ABORT_ERR is thrown if the current state is FileWriter.DONE or FileWriter.INIT.
FileTransferError
A FileTransferError
object is thrown when an error occurs.
Properties
- code: One of the predefined error codes listed below. (int)
Constants
FileTransferError.FILE_NOT_FOUND_ERR
FileTransferError.INVALID_URL_ERR
FileTransferError.CONNECTION_ERR
Description
The FileTransferError
object is thrown when an error occurs when uploading a file.