Created
March 31, 2020 14:41
-
-
Save shayc/df9c8d47f575523df24a926949901b40 to your computer and use it in GitHub Desktop.
JSZip example
This file contains 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
<input | |
type="file" | |
accept=".obf, .obz" | |
onChange={event => { | |
readFiles(event.target.files); | |
}} | |
/> | |
export async function readFiles(files: FileList): Promise<BoardSet[]> { | |
const obz = await parseOBZ(await readOBZFile(file)) | |
} | |
export function readOBZFile(file: File): Promise<JSZip> { | |
return jszip.loadAsync(file) | |
} | |
export function parseOBZ(zip: JSZip): Promise<BoardSet> { | |
return new Promise((resolve, reject) => { | |
const boardSet: BoardSet = { | |
manifest: { | |
format: '', | |
root: '', | |
paths: { | |
boards: {}, | |
images: {}, | |
sounds: {} | |
} | |
}, | |
boards: {}, | |
images: {}, | |
sounds: {} | |
} | |
let count = 0 | |
zip.forEach(async (relativePath: string) => { | |
count++ | |
const fileType = getFileType(relativePath) | |
const isBinary = fileType === 'sound' || fileType === 'image' | |
const asyncType = (isBinary && 'uint8array') || 'text' | |
const data = await zip.file(relativePath).async(asyncType) | |
switch (fileType) { | |
case 'sound': | |
boardSet.sounds[relativePath] = `data:audio/mp3;base64,${encode(data as Uint8Array)}` | |
break | |
case 'image': | |
boardSet.images[relativePath] = `data:image/png;base64,${encode(data as Uint8Array)}` | |
break | |
case 'board': | |
boardSet.boards[relativePath] = parseOBF(data as string) | |
break | |
case 'manifest': | |
boardSet.manifest = JSON.parse(data as string) | |
break | |
default: | |
// no default | |
} | |
if (!--count) { | |
resolve(boardSet) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment