Home > front end >  How do I write data binary to gcs with ruby efficiently?
How do I write data binary to gcs with ruby efficiently?

Time:03-26

I want to upload data binary directly to GCP storage, without writing the file to disk. Below is the code snippet I have created to get to the state that I am going to be at.

require 'google/cloud/storage'

bucket_name = '-----'

data = File.open('image_block.jpg', 'rb') {|file| file.read }


storage = Google::Cloud::Storage.new("project_id": "maybe-i-will-tell-u")
bucket  = storage.bucket bucket_name, skip_lookup: true

Now I want to directly put this data into a file on gcs, without having to write a file to disk.

Is there an efficient way we can do that?

I tried the following code

to_send = StringIO.new(data).read

bucket.create_file to_send, "image_inder_11111.jpg"

but this throws an error saying

/google/cloud/storage/bucket.rb:2898:in `file?': path name contains null byte (ArgumentError)
    from /home/inder/.gem/gems/google-cloud-storage-1.36.1/lib/google/cloud/storage/bucket.rb:2898:in `ensure_io_or_file_exists!'
    from /home/inder/.gem/gems/google-cloud-storage-1.36.1/lib/google/cloud/storage/bucket.rb:1566:in `create_file'
    from champa.rb:14:in `<main>'

CodePudding user response:

As suggested by @stefan, It should be to_send = StringIO.new(data), i.e. without .read (which would return a string again)

  • Related