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 objectvar xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {if (xhr.readyState == xhr.DONE) {if (xhr.status == 200 && xhr.response) {// The 'response' property returns an ArrayBuffersuccessCallback(xhr.response);} else {alert("Failed to download:" + xhr.status + " " + xhr.statusText);}}}
// Open the request for the provided urlxhr.open("GET", url, true);
// Set the responseType to 'arraybuffer' for ArrayBuffer responsexhr.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' eventsreader.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 failureif (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 ArrayBufferreader.readAsArrayBuffer(file);}
Комментариев нет:
Отправить комментарий