Created
January 26, 2017 10:19
-
-
Save akostadinov/21541a748cba28a55edca1d422ada949 to your computer and use it in GitHub Desktop.
ruby rest-client posting String as a file multipart/form-data
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
# 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