Search code examples
rubyopen-uri

Open URI downloading corrupt files


I am trying to download a .tar.gz file using Ruby. Upon download, the file is always corrupt in some way.

I am using this code to download the file:

require "open-uri"
File.open('img.tar.gz', 'wb') do |fo|
  fo.write open('https://github.com/Arafatk/language-basics/blob/master/img.tar.gz').read 
end

Is there a way to fix this?


Solution

  • Change the file mode in the open call:

    open('https://github.com/Arafatk/language-basics/blob/master/img.tar.gz', "rb").read
    

    It was opening the file in text mode, when you wanted binary mode.

    You also needed to be using the proper URL to download a raw file from Github. In this case, the correct URL can be found by right-clicking the Raw link on the file's repo page (the original URL given), and that Raw URL is the one that contains the actual binary image that you're trying to download. Change the URL to this: https://github.com/Arafatk/language-basics/raw/master/img.tar.gz, and the change I suggested at the top of the answer works just fine.