понедельник, 12 декабря 2011 г.

Getting Binary Data with XHR and File API

Before we can use the Typed Arrays APIs to work with the contents of files, we need to use browser APIs to get access to the raw data. For accessing files from the server, the XMLHttpRequest API has been extended with support for various “responseType”s. The “arraybuffer” responseType provides the contents of the requested server resource to JavaScript as an ArrayBuffer object. Also supported are the “blob,” “text” and “document” response types.
function getServerFileToArrayBufffer(url, successCallback) {
// Create an XHR object
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
if (xhr.status == 200 && xhr.response) {
// The 'response' property returns an ArrayBuffer
successCallback(xhr.response);
} else {
alert("Failed to download:" + xhr.status + " " + xhr.statusText);
}
}
}

// Open the request for the provided url
xhr.open("GET", url, true);

// Set the responseType to 'arraybuffer' for ArrayBuffer response
xhr.responseType = "arraybuffer";

xhr.send();
}
In many cases files are provided by the user, for example as an attachment to an email in a Web mail application. The File API offers Web developers tools to read the contents of files provided via an element, drag-and-drop or any other source that provides Blobs or Files. The FileReader object is used to read the contents of a file into an ArrayBuffer and, like the XHR object, is asynchronous to ensure that reading from the disk does not prevent the user interface from responding.
function readFileToArrayBuffer(file, successCallback) {
// Create a FileReader
var reader = new FileReader();

// Register for 'load' and 'error' events
reader.onload = function () {
// The 'result' property returns an ArrayBuffer for readAsArrayBuffer
var buffer = reader.result;
successCallback(buffer);
}

reader.onerror = function (evt) {
// The error code indicates the reason for failure
if (evt.target.error.code == evt.target.error.NOT_READABLE_ERR) {
alert("Failed to read file: " + file.name);
}
}

// Begin a read of the file contents into an ArrayBuffer
reader.readAsArrayBuffer(file);
}

Conclusion

Binary data is heavily used by Web browsers. With support for Typed Arrays, XHR2 and the File API in IE10, Web applications can now work directly with binary data, to manipulate byte-level data, to render additional binary data formats, and to extract data from existing media file formats. Try out the Binary File Inspector test drive demo, and take Typed Arrays for a spin in IE10.

Комментариев нет:

Отправить комментарий