Using send_file to download a file from Amazon S3?

前端 未结 7 1585
感动是毒
感动是毒 2020-11-29 18:10

I have a download link in my app from which users should be able to download files which are stored on s3. These files will be publicly accessible on urls which look somethi

7条回答
  •  鱼传尺愫
    2020-11-29 18:56

    Keep Things Simple For The User

    I think the best way to handle this is using an expiring S3 url. The other methods have the following issues:

    • The file downloads to the server first and then to the user.
    • Using send_data doesn't produce the expected "browser download".
    • Ties up the Ruby process.
    • Requires an additional download controller action.

    My implementation looks like this:

    In your attachment.rb

    def download_url
      S3 = AWS::S3.new.buckets[ 'bucket_name' ] # This can be done elsewhere as well,
                                                # e.g config/environments/development.rb
      url_options = { 
        expires_in:                   60.minutes, 
        use_ssl:                      true, 
        response_content_disposition: "attachment; filename=\"#{attachment_file_name}\""
      }
    
      S3.objects[ self.path ].url_for( :read, url_options ).to_s
    end
    

    In your views

    <%= link_to 'Download Avicii by Avicii', attachment.download_url %>
    

    That's it.


    If you still wanted to keep your download action for some reason then just use this:

    In your attachments_controller.rb

    def download
      redirect_to @attachment.download_url
    end
    

    Thanks to guilleva for his guidance.

提交回复
热议问题