There is a built-in attachment
method
that optionally takes a filename parameter. If the filename has
an extension (.jpg
, etc.) that extension
will be used to determine the Content-Type
header for the response.
The evaluation of the route will provide the contents of the attachment.
[~/sinatra/sinatra-download(master)]$ cat app.rb require 'sinatra' before do content_type :txt end get '/attachment?' do attachment 'file.txt' "Here's what will be sent downstream, in an attachment called 'file.txt'." endCuando visitamos la página con el navegador se nos abre una ventana para la descarga de un fichero que será guardado (por defecto) como
file.txt
.
Los contenidos de ese fichero serán:
[~/sinatra/sinatra-download(master)]$ cat ~/Downloads/file.txt Here's what will be sent downstream, in an attachment called 'file.txt'.
Véase la documentación del módulo Sinatra::Streaming
[~/sinatra/sinatra-download(master)]$ cat sending_file.rb require 'sinatra' get '/' do send_file 'foo.png', :type => 'img/png', :disposition => 'attachment', :filename =>'tutu.png', :stream => false end
The options are:
filename
file name, in response, defaults to the real file name.
last_modified
value for Last-Modified header, defaults to the file's mtime
.
type
content type to use, guessed from the file extension if missing.
disposition
used for Content-Disposition
, possible value: nil
(default), :attachment
and
:inline
length
Content-Length
header, defaults to file size.
status
Status code to be send.
Useful when sending a static file as an error page. If supported by the Rack handler, other means than streaming from the Ruby process will be used. If you use this helper method, Sinatra will automatically handle range requests.