2016-08-02 11 views
1

RubyZIPを使ってZIPファイルに既存のファイルを追加するには?私は次のようなコントローラのアクションを作成するために、<a href="https://github.com/rubyzip/rubyzip" rel="nofollow">RubyZIP</a>を使用しています私のRails 4.2のアプリケーションで

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" filename "を実行できますか? zip << File.binread( "file/path/and/filename") '? – matt

+0

それはうまくいった!ありがとう、@マット! – 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に追加するファイルの名前とパスがZIPファイルのパスですです。希望が助けてくれる!

+0

ありがとうございます。これは実際には機能しましたが、私の場合は不要なディスク上のファイルを作成します。 – Tintin81

関連する問題

 関連する問題