Force a link to download an MP3 rather than play it?

后端 未结 3 1507
星月不相逢
星月不相逢 2021-01-17 18:57

Ive got an anchor link

Download 

How do I ma

3条回答
  •  渐次进展
    2021-01-17 19:34

    Skip The Controller Action

    You don't even need the download controller action, you can just generate a download-friendly link like so:

    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=\"#{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 %>
    

    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.

提交回复
热议问题