Created
December 12, 2022 21:23
-
-
Save johannschopplich/31977a93771c670356f12c4b7c3964a2 to your computer and use it in GitHub Desktop.
Serialize FormData to object with support for Blobs
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
import { FormData as _FormData } from 'formdata-polyfill/esm.min.js' | |
export async function formDataToObject(formData: FormData) { | |
const obj: Record<string, any> = {} | |
for (const [key, value] of formData.entries()) { | |
if (value instanceof Blob) { | |
obj[key] = { | |
__type: 'blob', | |
...(await serializeBlob(value)), | |
} | |
} | |
else { obj[key] = value } | |
} | |
return obj | |
} | |
export function objectToFormData(obj: Record<string, any>) { | |
const formData = typeof FormData === 'undefined' ? new _FormData() : new FormData() | |
for (const [key, value] of Object.entries(obj)) { | |
if (typeof value === 'object' && value !== null && value.__type === 'blob') { | |
const arrayBuffer = Uint8Array.from(atob(value.data), c => c.charCodeAt(0)) | |
const blob = new Blob([arrayBuffer], { type: value.type }) | |
formData.append(key, blob, value.name) | |
} | |
else { | |
formData.append(key, value) | |
} | |
} | |
return formData | |
} | |
export function isFormData(obj: any): obj is FormData { | |
return typeof FormData !== 'undefined' && obj instanceof FormData | |
} | |
function serializeBlob(file: Blob) { | |
return new Promise<{ | |
data: string | |
type: string | |
size: number | |
}>((resolve, reject) => { | |
const reader = new FileReader() | |
reader.onload = () => { | |
const arrayBuffer = reader.result as ArrayBuffer | |
const bytes = new Uint8Array(arrayBuffer) | |
const binary = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), '') | |
const base64 = btoa(binary) | |
resolve({ | |
data: base64, | |
type: file.type, | |
size: file.size, | |
}) | |
} | |
reader.onerror = (error) => { | |
reject(error) | |
} | |
reader.readAsArrayBuffer(file) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment