diff --git a/Libraries/Blob/FileReader.js b/Libraries/Blob/FileReader.js index 57b3093cf6b025..3e20afe5c6e1a7 100644 --- a/Libraries/Blob/FileReader.js +++ b/Libraries/Blob/FileReader.js @@ -11,6 +11,7 @@ import type Blob from './Blob'; import NativeFileReaderModule from './NativeFileReaderModule'; +import {toByteArray} from 'base64-js'; const EventTarget = require('event-target-shim'); @@ -74,8 +75,35 @@ class FileReader extends (EventTarget(...READER_EVENTS): any) { } } - readAsArrayBuffer(): any { - throw new Error('FileReader.readAsArrayBuffer is not implemented'); + readAsArrayBuffer(blob: ?Blob): void { + this._aborted = false; + + if (blob == null) { + throw new TypeError( + "Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'", + ); + } + + NativeFileReaderModule.readAsDataURL(blob.data).then( + (text: string) => { + if (this._aborted) { + return; + } + + const base64 = text.split(',')[1]; + const typedArray = toByteArray(base64); + + this._result = typedArray.buffer; + this._setReadyState(DONE); + }, + error => { + if (this._aborted) { + return; + } + this._error = error; + this._setReadyState(DONE); + }, + ); } readAsDataURL(blob: ?Blob): void { diff --git a/Libraries/Blob/__tests__/FileReader-test.js b/Libraries/Blob/__tests__/FileReader-test.js index 1e1ac1ab7a4dd6..8e28b84c669f77 100644 --- a/Libraries/Blob/__tests__/FileReader-test.js +++ b/Libraries/Blob/__tests__/FileReader-test.js @@ -38,4 +38,16 @@ describe('FileReader', function () { }); expect(e.target.result).toBe('data:text/plain;base64,NDI='); }); + + it('should read blob as ArrayBuffer', async () => { + const e = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = resolve; + reader.onerror = reject; + reader.readAsArrayBuffer(new Blob()); + }); + const ab = e.target.result; + expect(ab.byteLength).toBe(2); + expect(new TextDecoder().decode(ab)).toBe('42'); + }); });