Creare un file zip al volo con ruby

By | 22 febbraio 2010

Recentemente, mi è stato chiesto di aggiungere ad una applicazione Ruby on Rails una funzionalità per il download di un’intera galleria di immagini in un unico file zip.

In modo abbastanza ovvio ho deciso di sfruttare la gemma rubyzip per creare l’archivio compresso da scaricare.

Ma ciò che volevo era creare lo zip al volo, direttamente in memoria, senza popolare le cartelle della mia applicazione di file zip che avrei poi dovuto rimuovere.

Da qui l’idea di utilizzare Tempfile per creare il file in memoria.

Di seguito la funzione “download_zip” che ho creato:

def download_zip(image_list)
    if !image_list.blank?
      file_name = ""
      t ="mio-file-temp-#{}") do |z|
        image_list.each do |img|
          title = img.title
          title += ".jpg" unless title.end_with?(".jpg")
      send_file t.path, :type => 'application/zip',
                             :disposition => 'attachment',
                             :filename => file_name

Ecco come lavora la funzione download_zip:

  • prende in input una lista di oggetti Image, dove Image ha le proprietà title e path relative all’immagine.
  • crea il file temporaneo e lo apre come uno ZipOutputStream.
  • per ogni immagine presente nella lista crea un nuovo elemento nello ZipOutputStream con nome uguale al titolo dell’immagine e contenuto letto dal path.
  • successivamente, la chiusura del blocco Zip::ZipOutputStream … end causa automaticamente la chiusura del nuovo file zip.
  • a questo punto non rimane altro che inviare il file all’utente con il corretto mime type.
  • infine, viene chiuso il file temporaneo, che sarà poi rimosso dalla memoria dal garbage collector.

Come vedete, con poche righe di codice si è ottenuta una soluzione molto pulita ed efficace.

Category: Svliluppo Ruby Tag:, ,

About Claudio

Claudio Marai is a co-founder of DevInterface.

After graduating in Computer Science has contributed to develop complex web applications based on Java/J2EE and desktop applications with the. NET framework for the Ministry of Justice and ultimately for the banking ambit.

The passion for web in recent years has led him to be interested in more modern frameworks such as Ruby on Rails and Django, and to a development approach based on agile methodologies such as eXtreme Programming and SCRUM.

22 thoughts on “Creare un file zip al volo con ruby

  1. ramzi“my-temp-filename-#{request.remote_ip}”)

    using the client ip address to generate a unique file is flawed…

    what happens if a user has more than one browser open, trying to download pictures?
    also, keep in mind that in many scenarios (universities, large corporations, fastweb), large subnets access the internet using a single IP address.

    a better solution would be

    keep up the great stuff!

  2. Claudio Post author

    Your observation is correct. Thank you for letting me see this “unforgivable” mistake. I’ve adjusted the example using a simple but effective workaround: ( “my-temp-filename-request.remote_ip # ()”)

    now becomes ( “my-temp-filename-# (”)

    so that the name is no more linked to the ip-address but rather to the download-time.

  3. Justin Powers

    Excellent tip, I will be using this for my website! My only comment is that it is still possible for two people to request zip files at the same time ( is accurate to the second), so I might either use a UUID (as Ramzi suggested), or just add a random number, like so:“my-temp-filename-#{ + rand(9999).to_s}”

    Also, since the files exist only in memory, and therefore likely only last a short amount of time, provides very little entropy. Just a thought!

  4. Ricardo Duarte


    I’ve got this error when using your code at line 12:

    wrong argument type String (expected Zip::Archive)

    11. t =“my-temp-filename-#{}”)
    12. do |z|

    What am i doing wrong?

  5. Claudio Post author

    Hi Ricardo,
    I’ve tried to reproduce your error without success.

    May be you’ve not included zip gems in your controller?

    Try with with:
    require ‘zip/zip’
    require ‘zip/zipfilesystem’

  6. Steve

    I’m getting all sorts of errors for this, namely that the images come out in the compressed folder corrupted, with bad filetypes and defintions.

    All of the zip creation and filenaming goes well, but when the file has been downloaded, the files just refuse to show due to either being corrupted (through ASCII conversion) or have bogus Huffman definitions which flag them as Qt-PICT exploits.

    Anyone else run into this issue?

  7. David

    Hey Steve, I am running into the same problem. I am on OS X running Ruby 1.9.1 .. whenever i try to unzip the resulting file Unarchiver tells me there is an error decrunching the file…

  8. Hamlet

    thanks for the tip about creating a zip file…
    But where did you see that Tempfile was creating a file in memory ?

    From the doc you linked :
    “Creates a temporary file of mode 0600 in the temporary directory”

    Otherwise it should fit your bill,

  9. Simon

    Thanks for the article but I think it would be even better to call

    this gives you the timestamp and will be an integer. The you use could contain all kind of strange characters (e.g. a slash or dots) which may pose some problems on certain file systems, don’t you think?

  10. Jose

    With Ruby 1.9.2 I found using z.write instead of z.print fixed my zip corruption problem.

  11. Koen

    this didn’t work for me on 1.8.7 in combination with heroku – i get an empty file – but when i closed the file and read it as data and streamed it as data with send_data than it does work. do |z|
    files.each do |wood, report|
    title = wood.abbreviation+”.txt”
    z.write report
    file =, “r”)
    data =
    send_data data, :type => ‘application/zip’, :disposition => ‘attachment’, :filename => file_name

  12. supernsetips

    Dude.. I am not much into reading, but somehow I got to read lots of articles on your website. Its amazing how interesting it is for me to visit you very often.

  13. Raphaël

    I’ve been using your code for an application coded in Rails 2.0.2 (Ruby 1.8.6).

    We had an issue that occurred very rarely: sometimes, during the send_file, the file was not found.

    After much investigation, we understood why: the send_file has an option (:stream) which defaults to true. If set to true, the file is read and sent on the fly. The problem is that in your code, you close and delete the temporary file just after the send_file.
    In our case, and maybe because we used an old version of Rails, the file was sometimes sent after being deleted (thus raising an error).

    The solution is just to add :stream => false:
    send_file t.path, :type => ‘application/zip’,
    :disposition => ‘attachment’,
    :filename => file_name,
    :stream => false

    With this option, the file is read BEFORE being sent, and then (and only then) closed.

    This option disappeared in Rails 3 (or around it) because it is handled in another way that I haven’t investigated.
    I’d suggest you to add this for people who, like me, would come to your blog and experience the same problem :)

  14. Pingback: Rails: on-the-fly streaming of output in zip format?

  15. Edward Rudd

    A few things to note. Tempfile doesn’t create file in memory (unless your tmp directory is in something like tmpfs). Also you do not need to put or anything of the sort in the first parameter to the constructor. takes a “basename” which is the prefix used to create the temporary filename.. the underlying make_tmpname method already mixes in the time and a random value.

  16. news

    If you dont mind, exactly where do you host your website? I am hunting for a great web host and your site seams to be quick and up most the time

Comments are closed.