Skip to content

Instantly share code, notes, and snippets.

@rddimon
Forked from ghinda/object-to-form-data.js
Last active August 22, 2018 12:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rddimon/af66932bc2e799606c5da912be3e6ea6 to your computer and use it in GitHub Desktop.
Save rddimon/af66932bc2e799606c5da912be3e6ea6 to your computer and use it in GitHub Desktop.
JavaScript Object to FormData, with support for nested objects, arrays and File objects. Version for Django Rest Framework.
// takes a {} object and returns a FormData object
var objectToFormData = function (obj, form, namespace) {
var fd = form || new FormData();
var formKey;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var propValue = obj[property];
if (namespace) {
formKey = namespace + '.' + property;
} else {
formKey = property;
}
// if the property is an object, but not a File and not an Array,
// use recursivity.
var isArray = Array.isArray(propValue);
var isFile = propValue instanceof File;
if (propValue instanceof Object && !isArray && !isFile) {
objectToFormData(propValue, fd, property);
} else if (isArray) {
propValue.map(function (item) {
var keyVal = {};
keyVal[formKey] = item;
objectToFormData(keyVal, fd);
})
} else {
// if it's a string or a File object
fd.append(formKey, propValue);
}
}
}
return fd;
};
// usage example
var z = objectToFormData({
obj: {
prop: 'property value'
},
arr: [
'one',
'two',
'three',
new File([''], '')
],
file: new File([''], '')
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(z);
// wrap object to formdata method,
// to use it as a transform with angular's http.
var formDataTransform = function (data, headersGetter) {
// we need to set Content-Type to undefined,
// to make the browser set it to multipart/form-data
// and fill in the correct *boundary*.
// setting Content-Type to multipart/form-data manually
// will fail to fill in the boundary parameter of the request.
headersGetter()['Content-Type'] = undefined;
return objectToFormData(data);
};
$http({
method: 'POST',
url: '/',
transformRequest: formDataTransform,
data: {your_object: {}}
}).success(function (res) {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment