Downloads / Descargas / Attachments

Usando attachment

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.

  1. Documentación de attachment
  2. Código de attachment en GitHub
  3. Upload and download files in Sinatra Random Ruby Thoughts

[~/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'." 
end
Cuando 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'.

Usando send_file

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:

  1. filename file name, in response, defaults to the real file name.
  2. last_modified value for Last-Modified header, defaults to the file's mtime.
  3. type content type to use, guessed from the file extension if missing.
  4. disposition used for Content-Disposition, possible value: nil (default), :attachment and :inline
  5. length Content-Length header, defaults to file size.
  6. 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.



Subsecciones
Casiano Rodriguez León 2015-06-18