Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Append content at the end of the existing s3 file using fog

How to append text in an existing or newly created file in S3. I am using fog and I have following code

require 'fog'
file    = "abc.csv"
bucket  = 'my_bucket'
storage = Fog::Storage.new(:provider => 'AWS', :aws_access_key_id => 'XXXXXXXX', :aws_secret_access_key => 'YYYYYYYY')
dir     = connection.directories.new(:key => bucket) # no harm, if this bucket already exists, if not create one
buffer  = ["big_chunk1", "big_chunk2", "big_chunk3", "big_chunk4", "big_chunk5"]

# I need help after this line. No changes above.
buffer.each do |chunk|
  # this will not work as it will not append text below the existing file or 
  # newly created one. I am not looking for solution suggesting, buffer.join('') 
  # and then write whole chunk at once. I have to write in chuck for some specific reason.
  # Also I dont want to first read existing data and then take in to memory
  # and then append and finally write back.
  dir.files.create(:key => file, :body => chunk, :public => false) 
end
like image 900
JVK Avatar asked Jan 25 '13 00:01

JVK


People also ask

Can we append data in S3?

Appending to Objects. AWS S3 does not offer a way to append to objects. Appending to an existing object is a different form of composing an object (see Composing Objects).

What does S3 Get_object return?

The #get_object method still returns a response object, but the #body member of the response will be the file object given as the :target instead of a StringIO object. You can specify the target as String or Pathname, and the Ruby SDK will create the file for you.

How do I append data in S3 bucket?

S3 doesn't have an "append" operation. Once an object has been uploaded, there is no way to modify it in place; your only option is to upload a new object to replace it, which doesn't meet your requirements.

Does S3 upload overwrite?

By default, when you upload the file with same name. It will overwrite the existing file. In case you want to have the previous file available, you need to enable versioning in the bucket.


1 Answers

Once uploaded to S3, a file is immutable - it cannot be changed or appended to.

If you a just looking to upload a file in chunks, you may be able to use the multipart upload api, (assuming you have under 10000 chunks and that all but the last will be at least 5MB), however you'd probably need to drop to the fog request level (instead of using the fog models as you are currently).

like image 179
Frederick Cheung Avatar answered Sep 22 '22 02:09

Frederick Cheung