2013-04-11 51 views
6

我有這樣的代碼,這將寫入一個zip文件到磁盤,讀回,上傳到S3,然後刪除該文件:Rubyzip:將zip文件直接導出到S3而不將tmpfile寫入磁盤?

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) 

此代碼的工作了,不過我想要是不能創建ZIP文件了,節省了幾個步驟。我想知道是否有辦法將zipfile數據直接導出到s3而不必先創建tmpfile,然後將其讀回,然後刪除它?

回答

8

我想我只是找到了我的問題的答案。

這是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') 

write_buffer回報StringIO,需要第一前read至來rewind流。現在我不需要創建和刪除tmpfile。

我只是想知道,如果write_buffer會更多的內存或比open重?或者是周圍的其他方式?

+0

什麼是'some_file_list'? – Trip 2013-11-07 06:16:27

+0

我猜它的東西像.. .. some_file_list = Zip :: ZipFile.open(zipped_file)' – Trip 2013-11-07 06:26:13

+0

可能。對我而言,我正在從S3閱讀我的文件。 – index 2013-11-07 07:10:05

相關問題