2016-08-02 127 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

相關問題