3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ruby で 画像ファイルをcurl POSTする

Posted at

ruby で画像ファイルを curl POST する際のテンプレートの一つとしてメモ。

curl_post.rb
require 'net/https'                                                                                                                        
require 'uri'
require 'open-uri'

file = open('path/to/image.jpg').read
url = URI.parse('https://url.co.jp')
data = [ 
 ['file', file, filename: file_name]
]   
 
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

req = Net::HTTP::Post.new(url.path)
req.set_form(data, "multipart/form-data")

http.request(req)

ポイントは set_form_data ではなく set_form を用いること。
画像ファイルという特性上multipart/form-dataが扱え、Rubyの標準ライブラリであるnet/httpを用いてPOSTできるようになる。

参考:Ruby で net/http を使ってファイルなどを multipart で POST する

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?