如何在rails上的ruby中发送多个“.Zip”文件

时间:2014-09-16 07:01:23

标签: 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文件之外的所有其他文件格式。如何完成?

2 个答案:

答案 0 :(得分:2)

我通过修改我的方法来解决它。我使用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

答案 1 :(得分:0)

rubyzip is a lib for creating / working with zip archives in ruby. 

    » gem install rubyzip


 Sample code

 require 'zip/zip'
 require 'zip/zipfilesystem'


 def download_all
 attachments = Upload.find(:all, :conditions => ["source_id = ?", params[:id]]) 

 zip_file_path = "#{RAILS_ROOT}/uploads/download_all.zip"


 # see if the file exists already, and if it does, delete it.
 if File.file?(zip_file_path)
 File.delete(zip_file_path)
 end


 # open or create the zip file
 Zip::ZipFile.open(zip_file_path, Zip::ZipFile::CREATE) { |zipfile|

 attachments.each do |attachment|
 #document_file_name shd contain filename with extension(.jpg, .csv etc) and url is the path of      the document.
 zipfile.add( attachment.document_file_name, attachment.document.url) 

 end

 } 
 #send the file as an attachment to the user.
 send_file zip_file_path, :type => 'application/zip', :disposition => 'attachment', :filename =>           "download_all.zip"

 end