Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force browser to download file instead of opening it

Tags:

ruby

sinatra

I would like to download http://foobar.com/song.mp3 as song.mp3, instead of having Chrome open it in its native <audio> player in the browser.

How can I accmplish this?

like image 606
Mark Avatar asked Feb 01 '11 22:02

Mark


People also ask

How do I force a file to download instead of open in browser?

Click on "Settings" and you'll see a new page pop up in your Chrome browser window. Scroll down to Advanced Settings, click Downloads, and clear your Auto Open options. Next time you download an item, it will be saved instead of opened automatically.

How do I make Chrome download instead of opening?

Alternatively, enter chrome://settings/content/ in the address bar. On the right, go to the Content section, and click on Additional content settings. Click on PDF documents. On the next page, turn on (enable) the Download PDF files instead of automatically opening them in Chrome option.


1 Answers

You just need to make sure to send these headers:

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

The send_file method does it for you:

get '/:file' do |file|
  file = File.join('/some/path', file)
  send_file(file, :disposition => 'attachment', :filename => File.basename(file))
end
like image 157
dontangg Avatar answered Oct 31 '22 21:10

dontangg