简体   繁体   中英

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. Incorrect number of files uploaded. Must upload exactly one file.

我删除了标题: req.headers['Content-Type'] = 'application/x-www-form-urlencoded'并使用了"filedata": Faraday::UploadIO.new(file_path, content_type)而不是字符串

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM