紅寶石'2.7.4'
導軌'?> 5.2.2'
我可以訪問包含多種型別的多個檔案的 S3 存盤桶,我正在嘗試
- 下載到記憶體
- 將它們全部放在一個 zip 檔案中
- 將此 zip 檔案上傳到某個 S3 存盤桶中
我已經在網上研究了幾個問題,但沒有任何成功。具體來說,我正在嘗試使用rubyzipgem,但無論我做什么,我總是以錯誤訊息結束:'沒有將 StringIO 隱式轉換為 String'
這是我當前代碼的摘要
gem 'rubyzip', require: 'zip'
require 'zip'
bucket_name = 'redacted'
zip_filename = "My final complete zip file.zip"
s3_client = Aws::S3::Client.new(region: 'eu-west-3')
s3_resource = Aws::S3::Resource.new(region: 'eu-west-3')
bucket = s3_resource.bucket(bucket_name)
s3_filename = 's3_file_name'
s3_file = s3_client.get_object(bucket: bucket_name, key: s3_filename)
file = s3_file.body
此時,我只有一個檔案,采用 StringIO 格式。 但是請記住,我試圖用幾個檔案來重現這個,這意味著我想將幾個檔案捆綁在一個最終的 zip 中。 我未能將此檔案放入 zip 和/或將 zip 放回 s3。
嘗試 N°1
stringio = Zip::OutputStream.write_buffer do |zio|
zio.put_next_entry("test1.zip")
zio.write(file)
end
stringio.rewind
binary_data = stringio.sysread
錯誤資訊 : no implicit conversion of StringIO into String
嘗試 N°2
zip_file_name = 'my_test_file_name.zip'
File.open(zip_file_name, 'w') { |f| f.puts(file.rewind && file.read) }
final_zip = Zip::File.open(zip_filename, create: true) do |zipfile|
zf = Zip::File.new(file, create: true, buffer: true)
zipfile.add(zf.to_s, zip_file_name)
end
really_final_zip = Zip::File.new(final_zip, create: true, buffer: true)
new_object = bucket.object(zip_file_name)
new_object.put(body: final_zip)
錯誤訊息: expected params[:body] to be a String or IO like object that supports read and rewind, got value #<Zip::Entry:0x0000558a06ff42a0
如果我寫的不是最后一行,
new_object.put(body: final_zip.to_s)
而是在 S3 中創建了一個文本檔案(而不是 zip),其內容為#<StringIO:0x0000558a06c8c8d8>
uj5u.com熱心網友回復:
需要從檔案中讀取位元組,所以......
更改
s3_file.body為s3_file.body.read
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445705.html
