Source: tiny/loaders/BinaryLoader.js

import * as core from '../core';

/**
 * 二进制数据加载
 *
 * @example
 *
 *  var loader = new Tiny.loaders.BinaryLoader('https://zos.alipayobjects.com/rmsportal/rFWpAALTVTmVcfiQMRAV.png');
 *  loader.load({
 *    onComplete: function (data) {
 *      console.log(data);
 *      // Uint8Array(895) [137, 80, 78, 71, 13...]
 *    }
 *  });
 *
 * @class
 * @memberof Tiny
 */
export default class BinaryLoader {
  /**
   *
   * @param {string}  url - 文件地址
   */
  constructor(url) {
    this._url = url;
  }

  /**
   * 执行加载
   *
   * @param {object}    opts
   * @param {function}  opts.onComplete 成功回调
   * @param {function}  opts.onError    失败回调
   */
  load(opts) {
    if (!opts) {
      opts = {};
    }

    const self = this;
    const xhr = core.getXMLHttpRequest();
    const onComplete = function (resourceLoader, resource) {
      (opts.onComplete || function () {
      })(resourceLoader, resource);
    };
    const onError = function (error, resourceLoader, resource) {
      const errorMsg = `${error}, url: ${resource.url}`;
      (opts.onError || function () {
        throw errorMsg;
      })(errorMsg, resourceLoader, resource);
    };

    xhr.open('GET', self._url, true);

    if (xhr.overrideMimeType) {
      xhr.overrideMimeType('ext/plain; charset=x-user-defined');
    }
    xhr.onload = function () {
      if (+xhr.readyState === 4 && +xhr.status === 200) {
        onComplete(self._str2Uint8Array(xhr.responseText));
      } else {
        onError();
      }
    };
    xhr.send(null);
  }

  /**
   *
   * @param strData
   * @return {Uint8Array}
   * @private
   */
  _str2Uint8Array(strData) {
    if (!strData) {
      return null;
    }

    const arrData = new Uint8Array(strData.length);
    for (let i = 0; i < strData.length; i++) {
      arrData[i] = strData.charCodeAt(i) & 0xff;
    }
    return arrData;
  }
}
Documentation generated by JSDoc 3.4.3 on Thu May 31 2018 14:40:21 GMT+0800 (CST)