所以基本上我试图下载一个pdf文件并将其上传到亚马逊桶上,是否可以在不创建临时文件的情况下完成?
要下载pdf im,请执行以下操作:
RestClient::Request.execute(
:method => :get,
:url => "#{@url}/test/#{id}/pdf",
:headers => json_headers.merge(jwt_headers(access_token))
) do |response|
disconnect if response.code == 401
return unless response.code == 200
response.body
end
但是我可以将response.body直接上传到amazon作为pdf吗? 我对rails很新,所以如果有更好的方法,或者这是完全错误的,请告诉我
答案 0 :(得分:0)
您可以使用s3 gem,S3库可以访问Amazon的Simple Storage Service。 检查here。
在您的Gemfile中添加s3 gem,以及代码下面的代码。
require 'open-uri'
require 's3'
aws_object = S3::Service.new(access_key_id: 'YOUR_ACCESS_KEY', secret_access_key: 'YOUR_SECRET_ACCESS_KEY') # Save it on server for security.
bucket = aws_object.buckets.find('bucket_name')
url = 'http://www.example.com/url' # Your file url
downloded_file = open(url)
new_file = bucket.objects.build('desired_file_name_with_extention')
new_file.content = (File.read downloded_file)
new_file.save
答案 1 :(得分:0)
如果您的文件已正确下载,那么您可以这样做,然后您可以一次上传,以便上传到s3
存储桶,您需要配置AWS S3
存储桶,然后按照以下步骤进行操作
在Gemfile
gem 'aws-sdk', '~> 2'
然后捆绑安装
# Configuration
Aws.config.update({
region: 'region_name', #=> like 'us-east-2'
credentials: Aws::Credentials.new('S3_ACCESS_KEY', 'S3_SECRET_KEY')
})
#=> do |response|
File.open("#{response.headers['content-id']}_#{response.headers['object-id']}.pdf", 'wb') do |f|
# Save pdf to application root folder
f.write(response.body)
s3 = Aws::S3::Resource.new(region:'us-east-2')
file_name = "#{Rails.root}/#{response.headers['content-id']}_#{response.headers['object-id']}.pdf"
bucket_name = 'S3_BUCKET_NAME'
# Upload this file to s3 bucket
key = File.basename(file_name)
obj = s3.bucket(bucket_name).object(key)
obj.upload_file(file_name, acl:'public-read')
# Remove this file from application root folder at a time if you don't need this in the future
#FileUtils.rm_f(file_name)
end
如果您需要在上传到s3
后删除此文件,请取消注释,如FileUtils.rm_f(file_name)