Created
October 5, 2023 13:49
-
-
Save gentoo90/b83a50680902fa2e29c7c16812d8edc3 to your computer and use it in GitHub Desktop.
rxjs-file-reader.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable, Subscriber } from 'rxjs'; | |
function readAs( | |
blob: Blob, | |
as: 'ArrayBuffer' | 'BinaryString' | 'DataURL' | 'Text', | |
encoding?: string | |
): Observable<any> { | |
return new Observable( | |
(subscriber: Subscriber<string | ArrayBuffer | null>) => { | |
const fileReader = new FileReader(); | |
fileReader.onload = (ev) => { | |
subscriber.next((ev.target as FileReader).result); | |
subscriber.complete(); | |
}; | |
fileReader.onerror = (error): void => { | |
subscriber.error(error); | |
}; | |
fileReader[`readAs${as}`](blob, encoding); | |
return () => { | |
fileReader.abort(); | |
}; | |
} | |
); | |
} | |
export function readAsArrayBuffer(blob: Blob): Observable<ArrayBuffer> { | |
return readAs(blob, 'ArrayBuffer'); | |
} | |
export function readAsBinaryString(blob: Blob): Observable<string> { | |
return readAs(blob, 'BinaryString'); | |
} | |
export function readAsDataURL(blob: Blob): Observable<string> { | |
return readAs(blob, 'DataURL'); | |
} | |
export function readAsText(blob: Blob, encoding?: string): Observable<string> { | |
return readAs(blob, 'Text', encoding); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment