【问题标题】:rubyzip: open zip, modify it temporary, send to clientrubyzip:打开 zip,临时修改,发送给客户端
【发布时间】:2020-03-16 12:20:52
【问题描述】:

我想临时修改一个 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 文件并将其他文件放入其中并在不保存磁盘的情况下发送它。

你能给我一个提示吗?

【问题讨论】:

    标签: ruby rubyzip


    【解决方案1】:

    最后我是这样做的:

    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
    

    【讨论】:

      【解决方案2】:

      查看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
      

      【讨论】:

      • 这将在磁盘上创建一个新文件。这是我想避免的事情..
      猜你喜欢
      • 2022-11-04
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2012-01-21
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多