123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- ; (function (global) {
- /**
- * 流式资源加载
- * @param {string} url 资源链接
- * @param {object} callbacks 回调集合:{onBuffer,onDone,onError}
- */
- class StreamingFetcher {
- constructor(url, callbacks) {
- this.url = url;
- this._isDone = false;
- this._error = null;
- this._abortController = new AbortController();
- this._callbacks = callbacks ?? {};
- }
- /**
- * Test Only
- */
- testCallback() {
- console.log("Hello!");
- this._callbacks.onDone();
- this._callbacks.onBuffer(new Uint8Array([1, 2, 3]));
- this._callbacks.onError("1234545");
- }
- /**
- * 停止加载
- */
- stop() {
- var isRunning = this._isDone === false && this._error == null;
- if (isRunning) {
- this._abortController.abort();
- }
- }
- /**
- * 开始加载
- */
- start() {
- var that = this;
- fetch(this.url, {
- signal: this._abortController.signal,
- keepalive: true,
- headers: {
- 'Accept-Ranges': 'bytes',
- 'Range': 'bytes=0-',
- 'Connection': 'keep-alive'
- }
- }).then(response => {
- const reader = response.body.getReader();
- function read() {
- reader.read().then(({ done, value }) => {
- if (done) {
- var onDone = that._callbacks.onDone;
- onDone && onDone();
- return;
- }
- var onBuffer = that._callbacks.onBuffer;
- onBuffer && onBuffer(value);
- // 读取下一个数据
- read();
- })
- }
- read();
- }).catch((error) => {
- that._error = error;
- var onError = that._callbacks.onError;
- onError && onError(error.message);
- });
- }
- }
- global.StreamingFetcher = StreamingFetcher;
- })(window);
|