Search code examples
ruby-on-railsrubyruby-on-rails-5facebook-messengerfaraday

How to send form data with Faraday and Rails 5?


I have the following Curl to send an attachment using Facebook Messenger API:

curl  \
  -F 'recipient={"id":"1234567890"}' \
  -F 'message={"attachment":{"type":"image", "payload":{}}}' \
  -F 'filedata=@/tmp/RackMultipart20191218-21313-lnjlid.png;type=image/png' \
  "https://graph.facebook.com/v5.0/me/messages?access_token=abcd"

And here is my code to send the form data:

    def send_attachment(to, file_data)
      url = send_message_url
      # conn = Connection.prepare_connection(url)
      conn = Faraday.new(url) do |f|
        f.request :multipart
        f.request :url_encoded
        f.adapter :net_http
        f.response :logger, Logger.new(STDOUT), bodies: true
      end
      response = Connection.post_form_request(conn, prepare_attachment(to, file_data))
      JSON.parse(response.body)
    end

    def prepare_attachment(to, file_data)
        {
          "recipient": JSON.dump(id:  to),
          "message": JSON.dump(attachment:  {
            "type": "image",
            "payload": {}
          }),
          "filedata": file_data
        }
        # file_data example: "@/tmp/RackMultipart20191218-2416-1ictdah.jpg;type=image/jpeg"
      end

Connection.post_form_request:

  def self.post_form_request(connection, body)
    connection.post do |req|
      req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      req.body = body
    end
  end

But right now I'm getting an error, it says Incorrect number of files uploaded. Must upload exactly one file.


Solution

  • I removed the headers: req.headers['Content-Type'] = 'application/x-www-form-urlencoded' and used "filedata": Faraday::UploadIO.new(file_path, content_type) instead of a string