【问题标题】:Ruby on Rails AWS S3 Download URLRuby on Rails AWS S3 下载 URL
【发布时间】:2018-03-12 13:15:11
【问题描述】:

如何为用户形成一个 url 链接,以便当用户单击该链接时,它会强制他们下载 AWS S3 对象?

我见过这两个解决方案:Using send_file to download a file from Amazon S3?Using send_file to download a file from Amazon S3? 但是,它们似乎引用了旧的 AWS S3 v1 SDK,并且 v2 AWS S3 SDK 中似乎没有 url_for。

谢谢。

【问题讨论】:

    标签: ruby-on-rails amazon-s3


    【解决方案1】:

    最终使用下面的代码sn-p来解决。希望这对其他人有帮助。

    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
    

    【讨论】:

      【解决方案2】:

      这是我得到的:

      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) 放入控制器操作中,然后创建指向该控制器操作的链接。

      【讨论】:

        猜你喜欢
        • 2010-11-23
        • 2013-12-23
        • 2015-03-28
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        • 1970-01-01
        • 2013-01-23
        • 1970-01-01
        相关资源
        最近更新 更多