强制链接下载MP3而不是播放?

时间:2011-05-13 07:46:24

标签: ruby-on-rails

我有一个锚链接

<a href="http://bucket_name.amazonaws.com/uploads/users/4/songs/7/test.mp3">Download</a> 

当用户点击它时,如何实现它,它实际上会打开一个弹出窗口,要求用户保存文件而不是尝试在浏览器上播放文件?

修改

我正在阅读article

  def download
    data = open(Song.first.attachment)
    send_data data.read, :type => data.content_type, :x_sendfile=>true
  end

本文建议使用x_sendfile,因为send_file会占用一个http进程,可能会挂起应用程序直到下载完成。

其次,我使用send_data而不是send_file,如果文件是远程的(即在Amazon S3上托管),这似乎有效。正如article所述。

我提到的那篇文章是在2009年发布的。是否还需要x_sendfile =&gt; true?如果不包含应用程序,它会挂起吗?

我真的应该使用send_data还是send_file?

3 个答案:

答案 0 :(得分:8)

如果您不想使用HTTP服务器配置,可以使用单独的控制器管理文件下载。

因此,disposition选项attachment可以send_file

答案 1 :(得分:5)

取决于您/文件本身的服务方式。我没有使用ruby的经验,但如果您可以更改http响应的标题(大多数平台提供此选项),您可以强制下载。这需要:

Content-Type: application/force-download

我猜它默认会使用“Content-type:application / octet-stream”,这会导致浏览器播放它。

但这只有在您控制保存实际文件的服务器/位置时才有效,因为您需要在将文件发送到浏览器时更改响应。

答案 2 :(得分:2)

跳过控制器操作

您甚至不需要download控制器操作,您只需生成类似下载的链接:

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

在您的观点中

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

如果您仍想出于某种原因继续执行download操作,请使用此功能:

attachments_controller.rb

def download
  redirect_to @attachment.download_url
end

感谢guilleva的指导。