LoginSignup
5

More than 5 years have passed since last update.

RubyのMechanizeで画像をPOSTする方法

Last updated at Posted at 2014-12-09

Rubyで画像をPOSTしたい

curl コマンドでもいいのですが、プログラムで画像をPOSTしたい時に、スクレイピングなどでも利用される Mechanize gem が使えるのでメモ。

Gemfile

source 'https://rubygems.org'

gem 'mechanize'

bundler でインストール

$ gem install bundler

$ bundle install --path vendor/bundle
run.rb
require 'mechanize'

# 画像のpathを指定
IMAGE_PATH  = '/path/to/sample.png'
# POSTするURLを指定
REQUEST_URL = 'http://moss.moss/api/image/uploader'

agent = Mechanize.new

# 処理を10回繰り返す
10.times do |i|
  response = agent.post(REQUEST_URL, {
    text: 'mossmossmoss', # 一緒にPOSTしたいデータがある時
    image:  File.open(IMAGE_PATH),
  })

  # responseがある場合にprintされる
  print "#{i+1}: #{response.code} #{response.body}\n"

  # sleep なんかを入れないと攻撃になってしまう
  sleep 3
end

スクリプトを走らせる

$ bundle exec ruby run.rb

responseがある場合の結果


1: {response.code} {response.body}
2: {response.code} {response.body}
3: {response.code} {response.body}
...
10: {response.code} {response.body}

sleepを入れないと、軽い攻撃になってしまう恐れがあるので注意が必要です。試す時はくれぐれも3秒待つ(sleep 3)などして優しくしてあげてください。

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
5