Skip to content

Instantly share code, notes, and snippets.

@jemsgit
Created May 17, 2024 15:23
Show Gist options
  • Save jemsgit/33ed596ae8d7799216986db648169470 to your computer and use it in GitHub Desktop.
Save jemsgit/33ed596ae8d7799216986db648169470 to your computer and use it in GitHub Desktop.
/**
* Creates multipart body for files with additional headers
* @param formData native FormData
* @param headers object: key - field name, value - object with header: value pairs
* @returns contentType and body
*/
function createMultipartBody(
formData: FormData,
headers: Record<string, AdditionalHeaders> = {},
) {
const boundary = `----WebKitFormBoundary${Math.random()
.toString(36)
.substring(2)}`;
let body = "";
// Create a Blob array to handle binary data properly
const blobs = [];
[...formData.entries()].forEach(([key, value]) => {
body += `--${boundary}\r\n`;
if (value instanceof File) {
body += `Content-Disposition: form-data; name="${key}"; filename="${value.name}"\r\n`;
body += `Content-Type: ${value.type || "application/octet-stream"}\r\n`;
if (headers[key]) {
const customHeaders = headers[key];
const headersString = Object.keys(customHeaders).reduce((acc, curr) => {
return `${acc}${curr}: ${customHeaders[curr]}\r\n`;
}, "");
body += headersString;
}
body += "\r\n";
blobs.push(new Blob([body], { type: value.type || "text/plain" }));
blobs.push(value);
body = "\r\n";
} else {
body += `Content-Disposition: form-data; name="${key}"\r\n\r\n`;
body += `${value}\r\n`;
blobs.push(new Blob([body], { type: "text/plain" }));
body = "";
}
});
body = `\r\n--${boundary}--\r\n`;
blobs.push(new Blob([body], { type: "text/plain" }));
const multipartBlob = new Blob(blobs, {
type: `multipart/form-data; boundary=${boundary}`,
});
return {
contentType: `multipart/form-data; boundary=${boundary}`,
body: multipartBlob,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment