Updated README.rdoc again
[feedcatcher.git] / vendor / rails / actionpack / lib / action_controller / streaming.rb
1 module ActionController #:nodoc:
2 # Methods for sending arbitrary data and for streaming files to the browser,
3 # instead of rendering.
4 module Streaming
5 DEFAULT_SEND_FILE_OPTIONS = {
6 :type => 'application/octet-stream'.freeze,
7 :disposition => 'attachment'.freeze,
8 :stream => true,
9 :buffer_size => 4096,
10 :x_sendfile => false
11 }.freeze
12
13 X_SENDFILE_HEADER = 'X-Sendfile'.freeze
14
15 protected
16 # Sends the file, by default streaming it 4096 bytes at a time. This way the
17 # whole file doesn't need to be read into memory at once. This makes it
18 # feasible to send even large files. You can optionally turn off streaming
19 # and send the whole file at once.
20 #
21 # Be careful to sanitize the path parameter if it is coming from a web
22 # page. <tt>send_file(params[:path])</tt> allows a malicious user to
23 # download any file on your server.
24 #
25 # Options:
26 # * <tt>:filename</tt> - suggests a filename for the browser to use.
27 # Defaults to <tt>File.basename(path)</tt>.
28 # * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
29 # either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
30 # * <tt>:length</tt> - used to manually override the length (in bytes) of the content that
31 # is going to be sent to the client. Defaults to <tt>File.size(path)</tt>.
32 # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
33 # Valid values are 'inline' and 'attachment' (default).
34 # * <tt>:stream</tt> - whether to send the file to the user agent as it is read (+true+)
35 # or to read the entire file before sending (+false+). Defaults to +true+.
36 # * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
37 # Defaults to 4096.
38 # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
39 # * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
40 # the URL, which is necessary for i18n filenames on certain browsers
41 # (setting <tt>:filename</tt> overrides this option).
42 # * <tt>:x_sendfile</tt> - uses X-Sendfile to send the file when set to +true+. This is currently
43 # only available with Lighttpd/Apache2 and specific modules installed and activated. Since this
44 # uses the web server to send the file, this may lower memory consumption on your server and
45 # it will not block your application for further requests.
46 # See http://blog.lighttpd.net/articles/2006/07/02/x-sendfile and
47 # http://tn123.ath.cx/mod_xsendfile/ for details. Defaults to +false+.
48 #
49 # The default Content-Type and Content-Disposition headers are
50 # set to download arbitrary binary files in as many browsers as
51 # possible. IE versions 4, 5, 5.5, and 6 are all known to have
52 # a variety of quirks (especially when downloading over SSL).
53 #
54 # Simple download:
55 #
56 # send_file '/path/to.zip'
57 #
58 # Show a JPEG in the browser:
59 #
60 # send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
61 #
62 # Show a 404 page in the browser:
63 #
64 # send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404
65 #
66 # Read about the other Content-* HTTP headers if you'd like to
67 # provide the user with more information (such as Content-Description) in
68 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
69 #
70 # Also be aware that the document may be cached by proxies and browsers.
71 # The Pragma and Cache-Control headers declare how the file may be cached
72 # by intermediaries. They default to require clients to validate with
73 # the server before releasing cached responses. See
74 # http://www.mnot.net/cache_docs/ for an overview of web caching and
75 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
76 # for the Cache-Control header spec.
77 def send_file(path, options = {}) #:doc:
78 raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
79
80 options[:length] ||= File.size(path)
81 options[:filename] ||= File.basename(path) unless options[:url_based_filename]
82 send_file_headers! options
83
84 @performed_render = false
85
86 if options[:x_sendfile]
87 logger.info "Sending #{X_SENDFILE_HEADER} header #{path}" if logger
88 head options[:status], X_SENDFILE_HEADER => path
89 else
90 if options[:stream]
91 render :status => options[:status], :text => Proc.new { |response, output|
92 logger.info "Streaming file #{path}" unless logger.nil?
93 len = options[:buffer_size] || 4096
94 File.open(path, 'rb') do |file|
95 while buf = file.read(len)
96 output.write(buf)
97 end
98 end
99 }
100 else
101 logger.info "Sending file #{path}" unless logger.nil?
102 File.open(path, 'rb') { |file| render :status => options[:status], :text => file.read }
103 end
104 end
105 end
106
107 # Sends the given binary data to the browser. This method is similar to
108 # <tt>render :text => data</tt>, but also allows you to specify whether
109 # the browser should display the response as a file attachment (i.e. in a
110 # download dialog) or as inline data. You may also set the content type,
111 # the apparent file name, and other things.
112 #
113 # Options:
114 # * <tt>:filename</tt> - suggests a filename for the browser to use.
115 # * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
116 # either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
117 # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
118 # Valid values are 'inline' and 'attachment' (default).
119 # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
120 #
121 # Generic data download:
122 #
123 # send_data buffer
124 #
125 # Download a dynamically-generated tarball:
126 #
127 # send_data generate_tgz('dir'), :filename => 'dir.tgz'
128 #
129 # Display an image Active Record in the browser:
130 #
131 # send_data image.data, :type => image.content_type, :disposition => 'inline'
132 #
133 # See +send_file+ for more information on HTTP Content-* headers and caching.
134 #
135 # <b>Tip:</b> if you want to stream large amounts of on-the-fly generated
136 # data to the browser, then use <tt>render :text => proc { ... }</tt>
137 # instead. See ActionController::Base#render for more information.
138 def send_data(data, options = {}) #:doc:
139 logger.info "Sending data #{options[:filename]}" if logger
140 send_file_headers! options.merge(:length => data.size)
141 @performed_render = false
142 render :status => options[:status], :text => data
143 end
144
145 private
146 def send_file_headers!(options)
147 options.update(DEFAULT_SEND_FILE_OPTIONS.merge(options))
148 [:length, :type, :disposition].each do |arg|
149 raise ArgumentError, ":#{arg} option required" if options[arg].nil?
150 end
151
152 disposition = options[:disposition].dup || 'attachment'
153
154 disposition <<= %(; filename="#{options[:filename]}") if options[:filename]
155
156 content_type = options[:type]
157 if content_type.is_a?(Symbol)
158 raise ArgumentError, "Unknown MIME type #{options[:type]}" unless Mime::EXTENSION_LOOKUP.has_key?(content_type.to_s)
159 content_type = Mime::Type.lookup_by_extension(content_type.to_s)
160 end
161 content_type = content_type.to_s.strip # fixes a problem with extra '\r' with some browsers
162
163 headers.merge!(
164 'Content-Length' => options[:length],
165 'Content-Type' => content_type,
166 'Content-Disposition' => disposition,
167 'Content-Transfer-Encoding' => 'binary'
168 )
169
170 # Fix a problem with IE 6.0 on opening downloaded files:
171 # If Cache-Control: no-cache is set (which Rails does by default),
172 # IE removes the file it just downloaded from its cache immediately
173 # after it displays the "open/save" dialog, which means that if you
174 # hit "open" the file isn't there anymore when the application that
175 # is called for handling the download is run, so let's workaround that
176 headers['Cache-Control'] = 'private' if headers['Cache-Control'] == 'no-cache'
177 end
178 end
179 end