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

我有一个锚链接

Download 

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

编辑:

我正在读这篇文章 。

  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上托管),这似乎有效。 正如本文所述 。

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

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

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

因此,您可以将带有disposition选项的send_file作为attachment

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

 Content-Type: application/force-download 

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

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

跳过控制器操作

您甚至不需要download控制器操作,您只需生成一个下载友好的链接,如下所示:

在你的attachment.rb

 def download_url S3 = AWS::S3.new.buckets[ 'bucket_name' ] # This can be done elsewhere as well, # eg 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的指导。