我知道这是一个经常被问到的问题,但我一直在努力克服它,尽管在这里研究了几个小时。我试图上传。xlsx文档到我的AWS S3桶,但是我收到这个错误:
Error while uploading the file '' to the bucket '': undefined method `bucket' for nil:NilClass
然而,我已经检查了我的代码,错误对我来说并不明显。我将在下面附上有问题的代码。
attr_reader :year, :month, :data, :bucket_name, :file_name, :path
def initialize(year:, month:, data:)
@year = year
@month = month
@data = data
end
def call
REPORTS.each do |report|
data = generate_report_data(report)
tmp_path = report_tmp_path(report)
save_report_to_file(data: data, path: tmp_path)
upload_file_to_bucket?(bucket_name, file_name, path )
end
end
def generate_report_data(report)
report_class = "Accounting::Datev::Reports::#{report.to_s.camelize}".constantize
report_class.new(year: year, month: month).call
end
def save_report_to_file(data:, path:)
prepare_dir(path)
Accounting::Datev::Utils::ExcelGenerator.new(data: data, path: path).call
end
def s3_resource
@s3_resource ||= ::Aws::S3::Resource.new(access_key_id: Settings.aws_pair&.app_key_id,
secret_access_key: Settings.aws_pair&.app_secret_key,
region: Settings.aws_pair&.s3_region)
end
def BUCKET_NAME
@bucket_name = s3.bucket('textract-console-eu-central-1-3469d743-084a-020378550')
end
def upload_file_to_bucket?( file_name, path, bucket_name)
s3 = @s3_resource
obj = s3.bucket(bucket_name).object('/tmp/test.xls')
obj.upload_file(path)
true
rescue StandardError => e
puts "Error while uploading the file '#{file_name}' to the bucket '#{bucket_name}': #{e.message}"
end
def report_tmp_path(report)
"/tmp/reports/#{year}/#{month}/#{report}.xls"
end
def prepare_dir(path)
dir = File.dirname(path)
FileUtils.mkdir_p(dir)
end
end
end
end
不幸的是,您没有说明异常是在哪一行引发的,也没有提供完整的堆栈跟踪。
但乍一看,有这个bucket
调用:
def BUCKET_NAME
@bucket_name = s3.bucket(...)
end
这里你在s3
上调用bucket
,但s3
变量不存在于你的代码中,也不存在s3
方法。因此,BUCKET_NAME
方法的所有调用必须失败。