强制浏览器下载文件而不是打开它

我想将http://foobar.com/song.mp3下载为song.mp3 ,而不是让Chrome在浏览器的原生播放器中打开它。

我怎么能这样做呢?

您只需要确保发送这些标头:

 Content-Disposition: attachment; filename=song.mp3; Content-Type: application/octet-stream Content-Transfer-Encoding: binary 

send_file方法为您完成:

 get '/:file' do |file| file = File.join('/some/path', file) send_file(file, :disposition => 'attachment', :filename => File.basename(file)) end