Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Last active April 14, 2021 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam-ngu/cf7acab50c9a3b54aa75d2d2d7c411e8 to your computer and use it in GitHub Desktop.
Save sam-ngu/cf7acab50c9a3b54aa75d2d2d7c411e8 to your computer and use it in GitHub Desktop.
Form Data demo
// payload to send in the API request
const payload = {
email: "example@example.com",
recipients: [
'test1@example.com',
'test2@example.com',
],
attachment: fileObject,
}
// creating a new FormData instance
const formData = new FormData();
for (let key in payload) {
let value = payload[key];
if (Array.isArray(value)) {
value.forEach((item, index) => {
// pack array content in FormData using the append method
// first argument is the key, and the second argument is the value
// the form data key should look something like: 'recipients[0]', 'recipients[1]'
formData.append(`${key}[${index}]`, item);
});
} else {
formData.append(key, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment