繁体   English   中英

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

[英]How to send multiple “.Zip” files in ruby on rails

我是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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM