我有以下Curl使用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"
这是我发送表单数据的代码:
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
但是现在我遇到一个错误,它显示为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)
代替了字符串