Rubyzip:直接将zip文件导出到S3而不将tmpfile写入磁盘?

ind*_*dex 8 ruby zip ruby-on-rails amazon-s3 rubyzip

我有这个代码,它将一个zip文件写入磁盘,将其读回,上传到s3,然后删除该文件:

compressed_file = some_temp_path

Zip::ZipOutputStream.open(compressed_file) do |zos|
  some_file_list.each do |file|
    zos.put_next_entry(file.some_title)
    zos.print IO.read(file.path)
  end
end # Write zip file

s3 = Aws::S3.new(S3_KEY, S3_SECRET)
bucket = Aws::S3::Bucket.create(s3, S3_BUCKET)
bucket.put("#{BUCKET_PATH}/archive.zip", IO.read(compressed_file), {}, 'authenticated-read')

File.delete(compressed_file)
Run Code Online (Sandbox Code Playgroud)

这段代码已经可以使用,但我想要的是不再创建zip文件,以节省一些步骤.我想知道是否有办法将zipfile数据直接导出到s3而不必先创建一个tmp文件,读回来然后删除它?

ind*_*dex 9

我想我刚刚找到了问题的答案.

它是Zip :: ZipOutputStream.write_buffer.当我开始工作时,我会检查出来并更新这个答案.

更新

它确实有效.我的代码现在是这样的:

compressed_filestream = Zip::ZipOutputStream.write_buffer do |zos|
  some_file_list.each do |file|
    zos.put_next_entry(file.some_title)
    zos.print IO.read(file.path)
  end
end # Outputs zipfile as StringIO

s3 = Aws::S3.new(S3_KEY, S3_SECRET)
bucket = Aws::S3::Bucket.create(s3, S3_BUCKET)

compressed_filestream.rewind
bucket.put("#{BUCKET_PATH}/archive.zip", compressed_filestream.read, {}, 'authenticated-read')
Run Code Online (Sandbox Code Playgroud)

write_buffer回报StringIO的,需要倒带之前先流read荷兰国际集团它.现在我不需要创建和删除tmpfile.

我现在只是想知道是否write_buffer会有更多的内存扩展或更重open?或者是周围的其他方式?

  • 对于那些混淆为什么你会收到像'NameError:uninitialized constant Zip :: ZipOutputStream`这样的错误的人来说,这是因为现在这个类叫做`Zip :: OutputStream`. (2认同)