Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active October 24, 2023 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/b5504b5bf4153442c7324f75c23c664a to your computer and use it in GitHub Desktop.
Save loilo/b5504b5bf4153442c7324f75c23c664a to your computer and use it in GitHub Desktop.
Promise Wrapper for FileReader

Promise Wrapper for FileReader

This is a simple wrapper for the FileReader API. It allows converting a Blob (and therefore a File as well) to either a plain text string, a data URL or an ArrayBuffer with a nice and clean Promise API.

Signature

This is the TypeScript signature of the readBlob function:

/**
 * Read a blob or file and convert it to another data type
 *
 * @param blob   The blob or file to read
 * @param target The format to target (defaults to "text")
 */
declare function readBlob(blob: Blob): Promise<string>
declare function readBlob(blob: Blob, target: 'text'): Promise<string>
declare function readBlob(blob: Blob, target: 'dataURL'): Promise<string>
declare function readBlob(blob: Blob, target: 'ArrayBuffer'): Promise<ArrayBuffer>

Usage

Usage is pretty difficult to visibly demonstrate without a surrounding DOM, so I made a demo on CodePen.

/**
* Read a blob or file and convert it to another data type
*
* @param {Blob} blob The blob or file to read
* @param {string} target The format to target
* Defaults to "text", might be one of
* "text", "dataURL" or "ArrayBuffer"
* @return {Promise}
*/
export function readBlob(blob, target = 'text') {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => {
resolve(reader.result)
}
reader.onerror = reject
reader[`readAs${target.slice(0, 1).toUpperCase()}${target.slice(1)}`](blob)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment