Software and Other Stuff


21 Jun 2011

Downloading and unzipping a file with ruby

Quick! I need to download a zip file from an HTTP server and unzip it! That's surely trivial with ruby... is it? Yes, it is. But! Turns out there are a bunch of zip handling gems out there, and I had to try a a couple before arriving to my final solution.

First, let's download the file. This particular resource is served via an HTTP POST method. Yeah, unusual for a zip file.

require 'net/http'

  url = "http://someweirdserver.com/a-zip-served-via-POST.zip"
  data = { "some-bizarre-params" => "which-are-needed" }

  zipbytes = Net::HTTP.post_form(URI.parse(url), data).body

Done. Moving forward, let's unzip the file. One detail to bear in mind, I have the zip file as a buffer (a String instance), and I don't want to go trough a tempfile to unzip it. The good news is that the zipruby gem can work off buffers.

require 'zipruby'

  Zip::Archive.open_buffer(zipbytes) do |zf|
    # this is a single file archive, so read the first file
    zf.fopen(zf.get_name(0)) do |f|
      unzipped = f.read
      # done! do something with the unzipped file.
    end
  end

Related Posts

28 Mar 2014
» Fun with Google's Apps Script! Batch Processing Gmail emails By Host
07 Oct 2013
» Graphs are Everywhere! An overview of GraphConnect San Francisco 2013
23 Jul 2013
» Using AngularJS with a Rails backend


The opinions expressed in this personal blog represent my own and not those of my employer. All data and information provided is for informational purposes only. This blog makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis.
adapt.960.gs  |  icons