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 Barbudas 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.

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

···

--
RMagick: http://rmagick.rubyforge.org/

Marcelo Barbudas 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")

···

--
Posted via http://www.ruby-forum.com/\.

Marcelo Barbudas 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.

TPR.

···

--
Posted via http://www.ruby-forum.com/\.