繁体   English   中英

使用 ruby sdk 将文件夹上传到 s3

[英]uploading folder to s3 with ruby sdk

我有一个脚本应该使用 aws-sdk 和 ruby 将本地文件夹上传到 s3。 据我从ruby了解到,文件需要一个一个上传,所以这里是使用的代码:

require 'aws-sdk'
require 'open3'
s3_bucket = ARGV[0]
debug = ARGV[1] || nil
@s3 = Aws::S3::Client.new(region: 'eu-west-1')
files = Dir[ File.join('srv', '**', '*') ].reject { |p| File.directory? p }
files.each do |f|
    o, e, s = Open3.capture3("gio info -a standard::content-type #{f}")
    abort(e) unless s.to_s.match(/exit 0/)
    content_type = o.split('standard::content-type: ')[1].strip
    s3_key = f.split('srv/lila/')[1]
    puts "Uploading #{f} with content-type #{content_type}" if debug
    File.open(f,'rb') do |file|     
        @s3.put_object({body: file, content_type: content_type, bucket: s3_bucket, key: s3_key})
    end
end

My local file name is like this: srv/lila/1.1.1/somename/index.html , only the file name is uploaded, and not the content.So when I go to the URL, I can see the name of the文件作为内容srv/lila/1.1.1/somename/index.html 我的 ruby 知识有限,我不确定这个脚本有什么问题。 你能帮忙吗?

你的问题是这一行:

resp = @s3.put_object({body: f, content_type: content_type, bucket: s3_bucket, key: s3_key})

在这种情况下, f不是File ,而是表示文件路径的String

body:接受StringStringIOFile object 作为参数。 在这种情况下,您传递的是一个String ,它会将其视为上传文件的内容。

相反,我建议进行以下更改:

  File.open(f,'rb') do |file| 
    @s3.put_object({body: file, content_type: content_type, bucket: s3_bucket, key: s3_key})
  end

现在file是一个实际的File object。

我还删除了resp ,因为该局部变量没有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM