2014-09-16 6 views
1

Я новичок в Ruby on Rails. Я работаю над проектом, где мне нужно отправить несколько файлов Zip клиенту.Как отправить несколько файлов «.Zip» в ruby ​​on rails

Я использую 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-файлов. Как это можно сделать?

ответ

1

Я решил его, изменив мой метод .I используется 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 
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