Skip to content

Instantly share code, notes, and snippets.

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 jtomaszewski/10988930 to your computer and use it in GitHub Desktop.
Save jtomaszewski/10988930 to your computer and use it in GitHub Desktop.
Method that transforms data[Hash] into FormData object.
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
@jtomaszewski
Copy link
Author

Here's how you can use it:

  AccountResource = $resource "/account.json", {},
    update:
      method: "PUT"
      transformRequest: httpTransformRequestToFormData
      headers:
        "Content-Type": undefined # Send FormData, not JSON

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment