Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FileReader#readAsArrayBuffer #36332

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions Libraries/Blob/FileReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import type Blob from './Blob';

import NativeFileReaderModule from './NativeFileReaderModule';
import {toByteArray} from 'base64-js';

const EventTarget = require('event-target-shim');

Expand Down Expand Up @@ -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;
Copy link

@cbjs cbjs Sep 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not working on react-native@0.72.4
empty buffer, return typedArray directly is fine.

this._setReadyState(DONE);
},
error => {
if (this._aborted) {
return;
}
this._error = error;
this._setReadyState(DONE);
},
);
}

readAsDataURL(blob: ?Blob): void {
Expand Down
12 changes: 12 additions & 0 deletions Libraries/Blob/__tests__/FileReader-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
SheetJSDev marked this conversation as resolved.
Show resolved Hide resolved
});