send a post request with multipart/form-data in ruby

main.rb
require 'net/http'
require 'uri'

# create the url to send the request to
url = URI.parse('http://www.example.com/upload')

# create a new net/http object
http = Net::HTTP.new(url.host, url.port)

# create a new post request with multipart/form-data
request = Net::HTTP::Post.new(url.path)
request["Content-Type"] = "multipart/form-data"

# set the file parameter field
file = File.open("/path/to/file", "rb")
request.body_stream = UploadIO.new(file, "application/octet-stream")

# set any additional fields
request.set_form_data({
  "field1" => "value1",
  "field2" => "value2"
})

# send the request
response = http.request(request)

# print the response body
puts response.body
681 chars
29 lines

In this example, we use the Net::HTTP library to send a post request with multipart/form-data, which is commonly used for uploading files. We create a new Net::HTTP::Post object and set the Content-Type header to multipart/form-data. We then set the file field using the UploadIO class which takes the file path and content type as arguments. Finally, we can set any additional fields using the set_form_data method. The response is received and printed to the console.

gistlibby LogSnag