Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Created January 26, 2017 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save akostadinov/21541a748cba28a55edca1d422ada949 to your computer and use it in GitHub Desktop.
Save akostadinov/21541a748cba28a55edca1d422ada949 to your computer and use it in GitHub Desktop.
ruby rest-client posting String as a file multipart/form-data
# rest-client recognizes files in multipart/form-data by checking
# the object type passed as the field content. We need to craft
# our string to appear as a file IO. `#stringfile` does that.
# An alternative approach is to just write string to a file and
# pass file IO to rest-client but this would be suboptimal
# provided we already have the content as a String.
def stringfile(string,
filename="file_#{rand 100000}",
type=MIME::Types.type_for("xml").first.content_type)
file = StringIO.new(string)
file.instance_variable_set(:@path, filename)
def file.path
@path
end
file.instance_variable_set(:@type, type)
def file.content_type
@type
end
return file
end
RestClient.post(
"my.url.example.com/api",
{multipart: true, somefieldname: stringfile(xunit_str)},
headers={content_type: "multipart/form-data", accept: :json}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment