2016-08-02 131 views
1

在我的Rails 4.2的应用程序,我使用RubyZIP创建一个类似于下面的控制器操作:如何使用RubyZIP将现有文件添加到ZIP文件?

class SomeController < ApplicationController 

    def some_action 
    file_stream = Zip::ZipOutputStream.write_buffer do |zip| 
     zip.put_next_entry "dir1/hello.txt" 
     zip.print "Hello" 
     zip.put_next_entry "dir2/hello.txt" 
     zip.print "World" 
    end 
    file_stream.rewind 
    respond_to do |format| 
     format.zip do 
     send_data file_stream.read, filename: "zip_file.zip" 
     end 
    end 
    end 

end 

在这个例子中的两个文件是动态创建并写入,然后将其保存为ZIP文件。

但是我怎样才能在ZIP文件中添加一个已经存在(!)的文件,例如:来自我的/app/assets/documents文件夹的PDF文件?

这应该更容易实现,但我找不到任何文档。

感谢您的任何帮助。

+1

你可以做'zip.put_next_entry“文件名”; zip << File.binread(“file/path/and/filename”)'? – matt

+0

工作!谢谢,@matt! – Tintin81

回答

2
zip_file = File.new(zip_file_path, 'w') 

Zip::File.open(zip_file.path, Zip::File::Create) do |zip| 
    zip.add(file_name, file_path) 
end 

zip_file 

这里,FILE_NAME和FILE_PATH是名称和要添加到您的zip文件,zip_file_path文件的路径是ZipFile中的路径。希望有所帮助!

+0

谢谢。这确实工作,但创建光盘上的文件,在我的情况下是不必要的。 – Tintin81

相关问题