要在這裏提出一個我自己的問題的答案,我認爲更適合我想要做的事情。這種方法確實沒有文件(沒有臨時文件)。
由於ZipFile進行了擴展,並且實際上只是ZipCentralDirectory中的一組便捷方法,因此您可以直接使用ZipCentralDirectory而不是ZipFile。這將允許您使用IO流來創建和編寫zip文件。另外扔在使用StringIO這種,你可以從一個字符串做:
# load a zip file from a URL into a string
resp = Net::HTTP.new("www.somewhere.com", 80).get("/some.zip")
zip_as_string = response.body
# open as a zip
zip = Zip::ZipCentralDirectory.read_from_stream(StringIO.new(zip_as_string))
# work with the zip file.
# i just output the names of each entry to show that it was read correctly
zip.each { |zf| puts zf.name }
# write zip back to an output stream
out = StringIO.new
zip.write_to_stream(out)
# use 'out' or 'out.string' to do whatever with the resulting zip file.
out.string
更新:
這實際上並沒有在所有的工作。它將編寫一個可讀的zip文件,但只有zip文件的「目錄」。所有內部文件都是0長度。進一步深入研究Zip實現,它看起來像只保存內存中的zip條目'元數據',並且它返回到底層文件以讀取其他所有內容。基於此,看起來不可能在不寫入文件系統的情況下使用Zip實現。
是不是Tempfile創建一個文件? – 2010-12-03 23:31:49