我正在使用wicked_pdf生成pdf文件,并希望将其上传到s3存储桶,因为heroku不能公开保存。但是面临问题如何上传或如何在保存路径中提供s3存储桶路径。
这是我的控制器代码: -
pdf = render_to_string :pdf => "user_detail"
# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
答案 0 :(得分:2)
您可以使用aws-sdk gem。
gem会在您的环境文件中查找AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY和AWS_REGION,因此您需要添加这些内容。您可以为存在存储桶的区域创建S3资源,并使用唯一的文件名创建对象,并调用upload_file,如下所示。
require 'aws-sdk'
file_name = 'your-file.pdf'
s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
obj = s3.bucket('your-s3-bucket-name').object(file_name)
puts "Uploading file #{file_name}"
obj.upload_file("/Users/username/path/to/#{file_name}")
puts "Done"
答案 1 :(得分:2)
除了Anurag Aryan回答,您还可以使用Aws::S3::Object#put。如果对象是字符串或不是磁盘上的文件的IO对象,则此选项非常有用:
filename = 'filename.pdf'
pdf = render_to_string :pdf => "user_detail"
s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
obj = s3.bucket('your-s3-bucket-name').object(filename)
# upload pdf data as a string
obj.put(body: pdf)
# or as an IO object
save_path = Rails.root.join('pdfs', filename)
File.open(save_path, 'wb') do |file|
file << pdf
obj.put(body: file)
end
答案 2 :(得分:1)
此S3 gem可以让您执行此pdf上传。需要传递存储桶名称,访问密钥ID,访问密钥密码。
filename = "invoice.pdf"
# render your pdf file
pdf = render_to_string(:pdf => filename, template: "invoice.html.erb")
# S3 upload Code goes here
service = S3::Service.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'])
bucket = service.buckets.find(ENV['S3_BUCKET_NAME'])
file = bucket.objects.build("invoices/#{filename}")
file.content = pdf
file.content_type = "application/pdf"
file.acl = :public_read
file.save
# Done, use the URL below as needed
s3url = "http://#{ENV['S3_BUCKET_NAME']}.s3.amazonaws.com/invoices/#{filename}"