front-hub/src/utils/jsonToFormdata.ts

44 lines
869 B
TypeScript
Raw Normal View History

2023-07-06 21:52:07 +00:00
import type { Attachment } from "@root/model/attachment";
type KeyValue<T = string> = {
[key: string]: T;
};
const convertBinaryStringToFile = ({
name,
content,
mimetype,
}: Attachment): File => {
const bytes = new Uint8Array(content.length);
for (let index = 0; index < content.length; index += 1) {
bytes[index] = content.charCodeAt(index);
}
const blob = new Blob([bytes], { type: mimetype });
return new File([blob], name, { type: blob.type });
};
export const jsonToFormdata = (
json: KeyValue<string | Attachment>
): FormData => {
const formData = new FormData();
for (const key in json) {
if (!key) continue;
const value = json[key];
if (typeof value !== "string") {
formData.append(key, convertBinaryStringToFile(value));
continue;
}
formData.append(key, value);
}
return formData;
};