首页 > 解决方案 > 使用 Ruby 将 CSV 负载上传到 Google 存储

问题描述

我正在尝试使用 Ruby 直接将字符串有效负载上传到 Google Storage。但是,如果不在磁盘中创建临时文件,似乎没有直接的方法可以做到这一点。

我正在使用 CSV 库来生成字符串有效负载。

当前方法建议将字​​符串有效负载存储在临时文件中,然后使用如下代码将文件上传到谷歌存储:

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  file = bucket.create_file local_file_path, file_name

有没有办法避免创建要上传的临时文件?

标签: rubycsvgoogle-cloud-platformgoogle-cloud-storage

解决方案


我找到了说明我们可以用来any File-like object such as StringIO直接上传字符串有效负载的文档。

这是我的代码:

require "google/cloud/storage"

storage = Google::Cloud::Storage.new

bucket = storage.bucket "my-todo-app"
bucket.create_file StringIO.new("Hello world!"), "hello-world.txt"

例如,转到Creating a File链接的部分

文档链接: https ://googleapis.dev/ruby/google-cloud-storage/latest/Google/Cloud/Storage/Bucket.html#create_file-instance_method


推荐阅读