Upload Files Using Faraday

Upload files using Faraday

It turns out that I needed to specify an adapter. Here's the code that ended up working.

conn = Faraday.new('http://myapi') do |f|
f.request :multipart
f.request :url_encoded
f.adapter :net_http # This is what ended up making it work
end

payload = { :file => Faraday::UploadIO.new('...', 'image/jpeg') }

conn.post('/', payload)

Upload file to S3 using Faraday

Great question! I ran into the same thing.

The hard part of this in including the file. This seems to work:

  def params
{
:key => key_prefix + file_name,
:aws_access_key_id => access_key_id,
:acl => "private",
:policy => encoded_policy,
:signature => encoded_signature
:file => Faraday::UploadIO.new(StringIO.new(<<FILECONTENTS>>), <<MIMETYPE>>)
}
end

post image with faraday as parameter

What about:

conn = Faraday.new(:url => 'http://0.0.0.0:9292' ) do |faraday|
faraday.request :multipart
end
payload = { :profile_pic => Faraday::UploadIO.new('avatar.jpg', 'image/jpeg') }
conn.post 'http://0.0.0.0:9292/', payload

Faraday multipart request with json & file data

Found that Faraday doesn't support mix multipart request (file upload with json/xml data). This is because mixing file and json data is not restful approach and should be avoided entirely. More discussion is happening here https://github.com/lostisland/faraday/issues/769

I have temporarily fixed the issue by patching Faraday::Mulitipart class to allow mixing JSON data,

class Faraday::Request::Multipart
def create_multipart(env, params)
boundary = env.request.boundary
parts = process_params(params) do |key, value|
if (JSON.parse(value) rescue false)
Faraday::Parts::Part.new(boundary, key, value, 'Content-Type' => 'application/json')
else
Faraday::Parts::Part.new(boundary, key, value)
end
end
parts << Faraday::Parts::EpiloguePart.new(boundary)

body = Faraday::CompositeReadIO.new(parts)
env.request_headers[Faraday::Env::ContentLength] = body.length.to_s
return body
end
end

But in long term one should change server implementation to avoid mix multipart requests.



Related Topics



Leave a reply



Submit