DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Sending Files With Sinatra

02.17.2010
| 9557 views |
  • submit to reddit
        How to send files (attachments) with Sinatra 0.9.4.

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

I found the documentation was misleading in some cases and plain wrong in others. The key lie is the method "signature":

  def send_file(path, opts={})

This is confusing because Sinatra only uses options if you specify the disposition to either "inline" or "attachment". Otherwise, it simply throws the File (which doesn't know/care about your options). It is not enough to simply call

  send_file('/my/file')

Although the documentation says File.basename will be uses as the default name, that simply isn't true. Using Firefox, I got "download" as the filename.