Using sendfile( ) would be impossible
here because the data does not exist as a file. The data must be buffered in memory,
and the whole operation runs in user mode. The entire file is processed several times by
user-mode code, which is a much more complicated process, as shown in Figure 4-2.
Figure 4-1. Serving files using sendfile( )
Figure 4-2. Serving files from the database
Client Linux Apache Rails
Filesystem DB
Client Linux Apache Rails
Filesystem DB
Large/Binary Objects | 105
Sending Data with X-Sendfile
Often you will need to send a file to the client for download after doing some processing
in Rails. The most common example is an access-controlled file??”you need
to verify that the logged-in user has the appropriate level of access before sending the
file, for example. The easy way to do this is with the send_file or send_data API
calls, which stream data from the server to the client:
class DataController < ApplicationController
before_filter :check_authenticated
def private_document
file = File.find params[:id]
send_file file.path if file
end
end
This method is easy, but it is slow if you are sending static files. Rails reads the file
and streams it byte-by-byte to the client. The X-Sendfile protocol makes this easy
and fast, by allowing Rails to do its processing but then offloading the ???heavy lifting???
to the web server (which may offload that processing to the operating system
kernel, as described previously).
Pages:
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165