ruby-on-rails - 如何在 ruby​​ on Rails 中发送多个 ".Zip"文件

标签 ruby-on-rails ruby-on-rails-4

我是 Ruby on Rails 新手。我正在开发一个需要向客户端发送多个 Zip 文件的项目。

我为此使用 RubyZip。

 def Download 
    unless params[:fileLists].nil?
       file_name = "Peep-#{Time.now.to_formatted_s(:number)}.zip"
       t = Tempfile.new("my-temp-filename-#{Time.now.to_formatted_s(:number)}")  
Zip::OutputStream.open(t.path) do |z|
          for _file in params[:fileLists] 
              unless _file.empty?
                if File.file? _file
                    #z.add(File.basename(_file),_file)
                    z.put_next_entry(File.basename _file)
                    z.print IO.read(_file)
        #send_file _file , disposition: 'attachment',status: '200'
                end
             end
          end
       end

       #Sending Zip file 
       send_file t.path, :type => 'application/zip',
                             :disposition => 'attachment',
                             :filename => file_name
       t.close                    
    end
  end
end

这对于除 Zip 文件之外的所有其他文件格式都可以正常工作。如何做到这一点?

最佳答案

我通过修改方法解决了这个问题。我使用 IO.binread(_file) 而不是 IO.read(_file) 来读取文件。

Zip::OutputStream.open(t.path) do |z|
          for _file in params[:fileLists] 
              unless _file.empty?
                if File.file? _file
                    #z.add(File.basename(_file),_file)
                    z.put_next_entry(File.basename _file)
                    z.print IO.binread(_file)

                end
             end
          end
       end

       #Sending Zip file 
       send_file t.path, :type => 'application/zip',
                             :disposition => 'attachment',
                             :filename => file_name

关于ruby-on-rails - 如何在 ruby​​ on Rails 中发送多个 ".Zip"文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25862491/

相关文章:

ruby-on-rails - 在使用 Rails 4.1 的第一个模型上使用带有连接和排序的 pluck

ruby-on-rails - 命名作用域、Lambdas 和 Procs 之间的区别

ruby-on-rails - 如何使用命令行参数启动 Rails 控制台?

ruby-on-rails - Rspec should match is false 但 eq 应该为真吗?

css - link_to 中的 rails 打印样式颜色

ruby-on-rails - Ruby url 到 html 链接转换

ruby-on-rails - Rails嵌套表单错误,子级必须存在

javascript - rails : Update view multiple times in 1 action

ruby-on-rails - rails 4 回形针 : undefined method `brand_logo_image_content_type' for #<Batch:0x431a408>

ruby-on-rails - rails 4 : How to send mail in a separate thread?