如何使用rubyzip gem压缩列表临时文件

时间:2019-02-22 09:43:15

标签: ruby-on-rails file ruby-on-rails-4 rubyzip

我有一个像这样的临时文件列表:

urls = [#<Tempfile:/tmp/down20190222-7434-18yoxw4.jpg>, #<Tempfile:/tmp/down20190222-7434-1r8c4y2.jpg>, #<Tempfile:/tmp/down20190222-7434-qpyiy1.JPG>, #<Tempfile:/tmp/down20190222-7434-q8xyup.mp4>]

现在我想压缩这些文件以供用户下载:

t = Tempfile.new('tmp-zip')
Zip::OutputStream.open(t.path) do |zos|
  urls.each do |file|
    zos.print IO.read(file)
  end
end

send_file t.path, :type => "application/zip", :filename => "myfile.zip"

t.close

但是我得到了错误closed stream excluded from capture: DSN not set 在此行:zos.print IO.read(file)。在这种情况下我怎么了? 这是我的完整代码:

if posts.present?
      urls = []
      posts.each do |post|
        urls << post.filestack_image_url if post.filestack_image_url.present?
        urls << post.photo_attributes('original')['url'] if post.photo.present?
        urls << post.filestack_video_url if post.filestack_video_url.present?
        urls << post.video_attributes('remote')['url'] if post.video.present?
      end

      urls = urls.collect {|url| download_url(url) }.compact

      t = Tempfile.new('tmp-zip')
      Zip::OutputStream.open(t.path) do |zos|
        urls.each do |file|
          zos.print IO.read(file.path.to_s.split("/")[-1])
        end
      end

      send_file t.path, :type => "application/zip", :filename => "Awesome.zip"

      t.close
end

0 个答案:

没有答案