Curl `-T/--upload-file` in Faraday
I had a bit of trouble trying to find docs on how to do a curl --upload-file
request with ruby. This flag is a special flag that tells curl
to generate a PUT
request with the body being the file(s) to upload to the remote server.
In my case, I wanted to upload a single file, and I accomplished this with the faraday
and faraday-multipart gem
:
require 'faraday'
require 'faraday-multipart'
conn = Faraday.new("https://example.com") do |f|
f.request :multipart
end
upload_file = File.open("./path/to/image.jpg")
conn.put("/file-upload") do |req|
req['Content-Type'] = 'image/jpeg'
req['Content-Length'] = upload_file.size.to_s
req.body = Faraday::Multipart::FilePart.new(
upload_file,
'image/jpeg'
)
end
Part of the magic here is that you need to explicitly set the Content-Type
and the Content-Length
header.
https://github.com/lostisland/faraday-multipart
Tweet