Skip to content

Instantly share code, notes, and snippets.

@knzai
Last active August 10, 2024 18:47
Show Gist options
  • Save knzai/c297fdd13739e1a844e4001142183459 to your computer and use it in GitHub Desktop.
Save knzai/c297fdd13739e1a844e4001142183459 to your computer and use it in GitHub Desktop.
WebComponent for simpler parsing of a file selector input into a bytearray (like to use in wasm file processing)
//attach a listener (to an `is` applied file selector) that will get the parsed byte array to use:
//<input is="file-byte-reader" id="file-input"
//$('#file-input').addEventListener("file-byte-reader:loaded", e => YOURHANDLER(e.detail));
class FileByteReader extends HTMLInputElement {
connectedCallback() {
this.type = "file";
this.addEventListener('change', this.onChange);
}
emit (type, detail = {}) {
let event = new CustomEvent(`file-byte-reader:${type}`, {
bubbles: false,
cancelable: false,
detail: detail
});
return this.dispatchEvent(event);
}
onFileLoad(event) {
this.emit('loaded', new Int8Array(event.target.result));
}
onChange() {
if (this.files.length == 0) { return }
Array.from(this.files).forEach(file => {
const fileReader = new FileReader();
fileReader.addEventListener('loadend', e => this.onFileLoad(e));
fileReader.readAsArrayBuffer(file);
});
}
}
customElements.define("file-byte-reader", FileByteReader, { extends: 'input'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment