我想使用Net::HTTP::multipart
从Heroku应用程序向Facebook发布新照片。
我有以下JSON对象:
{"message"=>"My message", "image"=>#<ActionDispatch::Http::UploadedFile:0x00000004242490 @original_filename="neEZYMAnBI.jpg", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"image\"; filename=\"/home/user/public/direct/fb_images/neEZYMAnBI.jpg\"\r\nContent-Type: application/octet-stream\r\n", @tempfile=#<File:/app/tmp/RackMultipart20110818-1-18qnwtj>>, "method"=>"post", "access_token"=>"my_access_token", "format"=>"json"}
我试图使用:
require 'net/http/post/multipart'
url = URI.parse('https://graph.facebook.com/me/photos?access_token=#{params[:access_token]}')
File.open(params[@tempfile]) do |jpg|
req = Net::HTTP::Post::Multipart.new url.path,
"file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
res = Net::HTTP.start(url.host, url.port) do |http|
http.request(req)
end
end
可是:
有人可以建议解决方案吗?
由于
答案 0 :(得分:1)
您已经可以使用File
TempFile
个实例(以及params[:image].tempfile
个实例)
删除所有File.open
内容,然后使用以下内容构建UploadIO
:
UploadIO.new(params[:image].tempfile, ...)
答案 1 :(得分:0)
如何使用该文件发送params [:message]以获取图片标题?
在Rails 4中,发布带有其他正常参数(如输入值)的文件应该如下所示
def model_params
require_params = params.require(:model).permit(:param_one, :param_two, :param_three, :avatar)
require_params[:avatar] = model_params[:avatar].present? ? UploadIO.new(model_params[:avatar].tempfile, model_params[:avatar].content_type, model_params[:avatar].original_filename) : nil
require_params
end
require 'net/http/post/multipart'
url = URI.parse('http://www.example.com/upload')
Net::HTTP.start(url.host, url.port) do |http|
req = Net::HTTP::Post::Multipart.new(url, model_params)
key = "authorization_key"
req.add_field("Authorization", key)
http.use_ssl = (url.scheme == "https")
http.request(req)
end
在你的情况下,只是
req = Net::HTTP::Post::Multipart.new(url.path,
{
"file" => UploadIO.new(params[:image].tempfile,
params[:image].content_type,
params[:image].original_filename),
"message" => params[:message]
})
更简单
params[:image] = UploadIO.new(params[:image].tempfile,
params[:image].content_type,
params[:image].original_filename)
req = Net::HTTP::Post::Multipart.new(url.path, params)