Rails streaming file download
Posted
by
Leonard Teo
on Stack Overflow
See other posts from Stack Overflow
or by Leonard Teo
Published on 2012-04-15T11:25:45Z
Indexed on
2012/04/15
11:29 UTC
Read the original article
Hit count: 224
ruby-on-rails
I'm trying to implement a file download with Rails. I want to eventually migrate this code to using S3 to serve the file. I've copied the Rails send_file code almost verbatim and I cannot seem to get it to stream a file to the user. What happens is that it sends 'a' file to the user, but the downloaded file itself simply contains the text.inspect of the Proc: #
What am I doing wrong here?
options = {}
options[:length] = File.size(file.path)
options[:filename] = File.basename(file.path)
send_file_headers! options
render :status => 200, :text => Proc.new { |response, output|
len = 4096
File.open(file.path, 'rb') do |fh|
while buf = fh.read(len)
output.write(buf)
end
end
}
Ps: I've read in a number of other posts that it's not advisable to send files through the Rails stack, and if possible serve using the web server, or in the case of S3 use the hashed URL it can provide. Yes, we really do want to serve the file through the Rails stack.
© Stack Overflow or respective owner