Ruby on rails 如何使用法拉第和Rails 5发送表单数据?
我使用以下方法发送附件: 这是我发送表单数据的代码:Ruby on rails 如何使用法拉第和Rails 5发送表单数据?,ruby-on-rails,ruby,ruby-on-rails-5,facebook-messenger,faraday,Ruby On Rails,Ruby,Ruby On Rails 5,Facebook Messenger,Faraday,我使用以下方法发送附件: 这是我发送表单数据的代码: 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
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\u表单\u请求:
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
但现在我得到一个错误,它说
上传的文件数量不正确。必须只上载一个文件。
我删除了标题:req.headers['Content-Type']='application/x-www-form-urlencoded'
,并使用了“filedata”:法拉第::UploadIO.new(文件路径,内容类型)
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