rubyzip: открыть zip, временно изменить его, отправить клиенту - PullRequest
0 голосов
/ 16 марта 2020

Я хочу временно изменить zip-файл и отправить измененный файл клиенту.

сейчас я создаю поток файлов и отправляю его:

  require 'zip'
  zip_stream = Zip::OutputStream.write_buffer do |zip|
    zip.put_next_entry 'new_folder/file'
    zip.print "some text"
  end

  zip_stream.rewind
  send_data zip_stream.read, type: 'application/zip', disposition: 'attachment', filename: 'thing.zip'

Я не понимаю, как я могу открыть существующий zip-файл в файловой системе, поместить в него дополнительный файл и отправить его без сохранения на диск.

Можете ли вы дать мне подсказку?

Ответы [ 2 ]

1 голос
/ 16 марта 2020

Проверьте это https://github.com/rubyzip/rubyzip

require 'rubygems'
require 'zip'

folder = "Users/me/Desktop/stuff_to_zip"
input_filenames = ['image.jpg', 'description.txt', 'stats.csv']

zipfile_name = "/Users/me/Desktop/archive.zip"

Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
  input_filenames.each do |filename|
    # Two arguments:
    # - The name of the file as it will appear in the archive
    # - The original file, including the path to find it
    zipfile.add(filename, File.join(folder, filename))
  end
  zipfile.get_output_stream("myFile") { |f| f.write "myFile contains just this" }
end
0 голосов
/ 17 апреля 2020

В итоге я сделал это так:

require 'zip'
zip_stream = Zip::OutputStream.write_buffer do |new_zip|

 existing_zip = Zip::File.open('existing.zip')
 existing_zip.entries.each do |e|
   new_zip.put_next_entry(e.name)
   new_zip.write e.get_input_stream.read
 end

 new_zip.put_next_entry 'new_file'
 new_zip.print "text"
end
...