Created
April 17, 2014 14:45
-
-
Save jtomaszewski/10988930 to your computer and use it in GitHub Desktop.
Method that transforms data[Hash] into FormData object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module 'gulliver' | |
# This will transform data[Hash] into FormData object. | |
# Supports nested objects and FileList (file input's value). | |
# | |
# Note: This won't work on browsers not supporting FormData and FileList (f.e. IE 8-9). | |
.service 'httpTransformRequestToFormData', -> | |
(data) -> | |
return data unless data | |
getFormDataKey = (fieldName, prefixNames = []) -> | |
prefixNames = prefixNames.slice(0) | |
if prefixNames.length | |
key = prefixNames.shift() | |
key += "[#{name}]" while name = prefixNames.shift() | |
key += "[#{fieldName}]" | |
key | |
else | |
fieldName | |
appendHash = (fd, data, prefixNames = []) -> | |
angular.forEach data, (value, fieldName) -> | |
if value instanceof FileList | |
if value.length == 1 | |
fd.append getFormDataKey(fieldName, prefixNames), value[0] | |
else | |
angular.forEach value, (file, index) -> | |
fd.append getFormDataKey("#{fieldName}_#{index}", prefixNames), file | |
else if angular.isFunction(value) | |
# do nth | |
else if angular.isObject(value) | |
appendHash fd, value, prefixNames.concat([fieldName]) | |
else | |
fd.append getFormDataKey(fieldName, prefixNames), value | |
fd = new FormData | |
appendHash(fd, data) | |
fd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's how you can use it: