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

后端 未结 5 2087
忘掉有多难
忘掉有多难 2020-12-15 06:54

I need to serve some data from my database in a zip file, streaming it on the fly such that:

  • I do not write a temporary file to disk
  • I do not compose
5条回答
  •  离开以前
    2020-12-15 07:36

    I had a similar issue. I didn't need to stream directly, but only had your first case of not wanting to write a temp file. You can easily modify ZipOutputStream to accept an IO object instead of just a filename.

    module Zip
      class IOOutputStream < ZipOutputStream
        def initialize io
          super '-'
          @outputStream = io
        end
    
        def stream
          @outputStream
        end
      end
    end
    

    From there, it should just be a matter of using the new Zip::IOOutputStream in your Proc. In your controller, you'd probably do something like:

    self.response_body =  proc do |response, output|
      Zip::IOOutputStream.open(output) do |zip|
        my_files.each do |file|
          zip.put_next_entry file
          zip << IO.read file
        end
      end
    end
    

提交回复
热议问题