Streaming Files to the Browser with Ruby on rails
Quite often when building a web application you need to store and send Documents, with ruby on rails, streaming files from your application to the browser is simple.
def download_file
@document = Document.find(params[:id])
# this is where the magic happens...
send_file @document.file_location
end
This single line of code will stream a file from your servers filesystem directly to your browser.
The simple use described above is often enough but you have even further control over the file with the following options:
Options:
- :filename – suggests a filename for the browser to use. Defaults to File.basename(path).
- :type – specifies an HTTP content type. Defaults to ‘application/octet-stream’.
- :disposition – specifies whether the file will be shown inline or downloaded. Valid values are ‘inline’ and ‘attachment’ (default).
- :stream – whether to send the file to the user agent as it is read (true) or to read the entire file before sending (false). Defaults to true.
- :buffer_size – specifies size (in bytes) of the buffer used to stream the file. Defaults to 4096.
- :status – specifies the status code to send with the response. Defaults to ‘200 OK’.
- :url_based_filename – set to true if you want the browser guess the filename from the URL, which is necessary for i18n filenames on certain browsers (setting :filename overrides this option).
Pay particular notice to the :disposition option, changing this from its default to ‘inline’ will enable you to display the contents of the file in the browser window rather than downloading it as an attachment.
def download_file
@document = Document.find(params[:id])
# this is where the magic happens (inline)...
send_file @document.file_location, :disposition => "inline"
endThis is especially useful for things like word or excel documents when you know you target audience can read these in the browser.
EDGE RAILS
If you are brave enough to live on the Edge with Edge Rails you will get an extra treat for free, on Edge Rails the send_file method passes the correct information to your balancing server to allow it to stream the file rather than blocking your mongrel server.
Categories
CodeSpaces.com
Code Spaces is an online development and collaboration service that includes: Subversion Hosting, Project Management, Work Items, Forums, and much more.
Syndicate
Archives
- September 2010
- August 2010
- July 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009