LoginSignup
43
42

More than 5 years have passed since last update.

ファイルをWebからダウンロードして保存する

Last updated at Posted at 2012-12-26
download.rb
require 'open-uri'
@path = 'http://example.com/files/test.txt'

fileName = File.basename(@path)

open(fileName, 'wb') do |output|     #※1
  open(@path) do |data|
    output.write(data.read)          #※2
  end
end

※1
指定できるアクセスモード

  • r: 読み込みモード
  • w: 書き込みモード(上書き)
  • a: 書き込みモード(追記)
  • +: 読み書き両用モード(他のアクセスモードと組み合わせて使用)
  • b: バイナリモード(他のアクセスモードと組み合わせて使用)

画像や動画などをダウンロードする際は、バイナリ指定

※2
ファイルはRubyの作業フォルダ(このRubyファイルと同階層)に保存されます。

43
42
2

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
43
42