[英]Rails - Sending image using Faraday
I'm trying to make a request to an API sending an image and some other data, and getting the response. 我正在尝试向API发送图像和其他数据的请求,并获取响应。 That's my code:
那是我的代码:
file = "assets/images/test.jpg"
conn = Faraday.new(:url => "api_url" ) do |faraday|
faraday.request :multipart
end
payload = { :profile_pic => Faraday::UploadIO.new(file, 'image/jpeg') }
conn.post "/test", payload
My first problem is that I'm always getting the following error: 我的第一个问题是,我总是遇到以下错误:
Errno::ENOENT (No such file or directory - assets/images/test.png)
I've tried all the paths I could imagine. 我已经尝试了所有我能想象的路径。 Where should be saved the image in directories to be found by Faraday?
该图像应保存在法拉第要找到的目录中的什么位置?
The second question is about the response, how can I get the response and handle it? 第二个问题是响应,如何获得响应并进行处理?
The third one is that, I haven't understand what's the utility of the first parameter of the last call: 第三个是,我不知道最后一次调用的第一个参数的用途是什么:
conn.post "/hello", payload
I've written "/hello" but don't have any idea about what's the real usage. 我已经写了“ / hello”,但是对真正的用途一无所知。
And the last one. 还有最后一个。 Could I send a raw image saved in a variable instead of sending a path to Faraday?
我可以发送保存在变量中的原始图像,而不是发送到法拉第的路径吗?
EDIT 编辑
Now it's working, this is the solution: Be aware that url must be only until .com
, the rest of the path must go on conn.post
like this example /v1/search
. 现在可以正常工作了,这是解决方案:请注意url必须仅直到
.com
为止,其余路径必须在conn.post
,如此示例/v1/search
。 c.adapter :net_http
was needed too. c.adapter :net_http
也需要。 Message response is correctly handled in json variable. 消息响应已在json变量中正确处理。
Solution: 解:
url = 'http://url.com'
file = Rails.root.to_s + "/app/assets/images/test.jpg"
conn = Faraday.new(:url => url ) do |c|
c.request :multipart
c.adapter :net_http
end
payload = { :image => Faraday::UploadIO.new(file, 'image/jpeg'), :token => token}
response = conn.post '/v1/search', payload
json = JSON.parse response.body
You should try this for your first question : 您应该针对第一个问题尝试以下操作:
file = Rails.root.to_s + "/app/assets/images/test.jpg"
For your third question, the first parameters allows you to construct the right URL from the base "api_url". 对于第三个问题,第一个参数允许您从基本“ api_url”构建正确的URL。 Please see the example from the Readme .
请参阅自述文件中的示例。
## POST ##
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.