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

后端 未结 3 1483
星月不相逢
星月不相逢 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.

    0 讨论(0)
  • 2021-01-17 19:54

    You can manage your file downloading with separate controller, if you don't want to eal with HTTP server configurations.

    So you can send_file with disposition option as attachment.

    0 讨论(0)
  • 2021-01-17 19:58

    Depends on how you / where you serve the file itself. I do not have experience with ruby but if you can alter the headers(most platforms offer this option) of the http response you can force a download. This requires:

    Content-Type: application/force-download
    

    I guess it will use "Content-type: application/octet-stream" by default which will cause the browser to play it.

    But this will only work if you have control over the server/location that holds the actual file since you need to change the response when the file is sent to the browser.

    0 讨论(0)
提交回复
热议问题