Downloading files

Hi,

Which is the proper way to download a binary file?

Trying:
open(temp_path,“w”).write(open(http_path).read)

returns truncated files

Cheers,
M.

Marcelo B. wrote:

M.

Are you on Windows? Try opening the output file as “wb” instead of just
“w”.

Here’s a snippet from my RMagick OS X installer script. Ara Howard gave
me the code. ‘uri’ is the input URI, something like
http://rubyforge.org/frs/download.php/39890/RMagick-2.5.2.tar.gz

   begin
     open(uri) do |fin|
       open(File.basename(uri), "w") do |fout|
         while (buf = fin.read(8192))
           fout.write buf
         end
       end
     end
   rescue Timeout::Error
     abort <<-END_HTTP_DL_TIMEOUT
     A timeout occurred while downloading #{uri}.
     Probably this is a temporary problem with the host.
     Try again later.
     END_HTTP_DL_TIMEOUT
   end

Marcelo B. wrote:

Hi,

Which is the proper way to download a binary file?

Trying:
open(temp_path,“w”).write(open(http_path).read)

returns truncated files

Cheers,
M.

here is a snippet that should work :

require “rubygems”
require “mechanize”

agent = WWW::Mechanize.new
agent.get(link_to_download).save_as(“name_of_the_file”)

Marcelo B. wrote:

Hi,

Which is the proper way to download a binary file?

Trying:
open(temp_path,“w”).write(open(http_path).read)

returns truncated files

Cheers,
M.

Without Mechanize, it’s in fact better to do it in two lines:

data=open(remote).read
File::open(local,“wb”){|f| f<<data}

Because now you don’t create an empty file in case of net error.
http://al2o3-cr.blogspot.com/2008/08/downloading-file.html

TPR.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs