将多部分表单从curl转换为ruby,上传文件并包含json

时间:2017-01-26 10:32:21

标签: ruby curl

我需要转换包含一些json的多部分表单并上传文件。

curl \
-F metadata='{"userID":"12345","mimeType":"image/jpeg","typeHint": "uploadedImage" }' \
-F contents=@$HOME/Downloads/photo.jpg \
http://localhost:8083/myservice/upload

1 个答案:

答案 0 :(得分:1)

使用curl

按原样

显而易见的答案是从Ruby调用给定的命令:

curl_command = %q(curl -F metadata='{"userID":"12345","mimeType":"image/jpeg","typeHint": "uploadedImage" }' -F contents=@$HOME/Downloads/photo.jpg http://localhost:8083/myservice/upload)

system(curl_command)

%q()用于定义字符串,因为您有许多字符需要非转义(例如"'

参数

如果您需要动态参数,可以使用:

def curl_command(user_id, file, url)
  %Q(curl -F metadata='{"userID":"#{user_id}","mimeType":"image/jpeg","typeHint": "uploadedImage" }' -F contents=#{file} #{url})
end

picture = File.join(Dir.home, 'Downloads', 'photo.jpg')
puts curl_command(12345, picture, "http://localhost:8083/myservice/upload")
#=> curl -F metadata='{"userID":"12345","mimeType":"image/jpeg","typeHint": "uploadedImage" }' -F contents=/home/eric/Downloads/photo.jpg http://localhost:8083/myservice/upload

system(curl_command(12345, picture, "http://localhost:8083/myservice/upload"))

使用路缘

看起来curb宝石可以做你想做的事情:

  

HTTP POST文件上传:

c = Curl::Easy.new("http://my.rails.box/files/upload")
c.multipart_form_post = true
c.http_post(Curl::PostField.file('thing[file]', 'myfile.rb'))