如何为用户形成一个URL链接,使得当用户点击该链接时,它会强制下载AWS S3对象?我看到了这两个解决方案:使用send_file从Amazon S3下载文件?和使用send_file从Amazon S3下载文件?然而,它们似乎引用了旧的AWS S3 v1 SDK,并且在v2 AWS S3 SDK中似乎没有url_for。感谢您的帮助。
最终使用以下代码片段解决了问题。希望这能帮助其他人。
presigner = Aws::S3::Presigner.new
url = presigner.presigned_url(:get_object, #method
bucket: ENV['S3_BUCKET'], #name of the bucket
key: s3_key, #key name
expires_in: 7.days.to_i, #time should be in seconds
response_content_disposition: "attachment; filename=\"#{filename}\""
).to_s
以下是我得到的内容:
def user_download_url(s3_filename, download_filename=nil)
s3_filename = s3_filename.to_s # converts pathnames to string
download_filename ||= s3_filename.split('/').last
url_options = {
expires_in: 60.minutes,
response_content_disposition: "attachment; filename=\"#{download_filename}\""
}
object = bucket.object(s3_filename)
object.exists? ? object.presigned_url(:get, url_options).to_s : nil
end
def bucket
@bucket ||= Aws::S3::Resource.new(region: ENV['AWS_REGION']).bucket(ENV['AWS_S3_BUCKET'])
end
redirect_to user_download_url(s3_file_path)
,并创建指向该控制器操作的链接。