Skip to content

Instantly share code, notes, and snippets.

@iyobo
Created January 14, 2018 02:17
Show Gist options
  • Save iyobo/16e8ef2e901013df608ad78b7d41f335 to your computer and use it in GitHub Desktop.
Save iyobo/16e8ef2e901013df608ad78b7d41f335 to your computer and use it in GitHub Desktop.
Sadly most Ajax libraries (e.g axios) do not support automatic JS object to formData conversion. This is necessary for when you need to submit a form with a file, for example.
/**
* Created by iyobo on 2017-04-25.
*/
function appendRecursively(formData, collection, parentkey, parentIsArray) {
//console.log(...arguments)
for (let k in collection) {
const val = collection[k];
if (val === undefined) continue;
if (val instanceof File) {
let mkey = (parentkey ? parentkey + '.' : '') + k;
// if(parentIsArray)
// mkey = parentkey
// else
// mkey = k
val.foo = 'bar'
formData.append(mkey, val)
}
else if (Array.isArray(val)) {
let mkey = '';
if (parentIsArray) {
mkey = parentkey; //parentKey can/should never be empty if parentISarray
} else {
mkey = (parentkey ? parentkey + '.' + k : k);
}
appendRecursively(formData, val, mkey, true);
}
else if (typeof val === 'object') {
let mkey = (parentkey ? parentkey + '.' : '') + k;
appendRecursively(formData, val, mkey, false);
}
else {
let mkey = (parentkey ? parentkey + '.' : '') + k;
formData.append(mkey, val)
}
}
}
export default function convertToFormData (data) {
var formData = new FormData();
appendRecursively(formData, data);
return formData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment