JSON compatible with Ry Dahl's Ajax.Pull + example
[upr.git] / examples / rails_app-2.3.4 / app / controllers / files_controller.rb
bloba0fdbb1cd8aaf4794653a7f02610f7eccb99b64a
1 require 'digest/sha1'
3 class FilesController < ApplicationController
4   # used by jQuery streaming upload progress
5   def new
6     _sha1_flash_self
7   end
9   # based on Ry Dahl's streaming AJAX pull:
10   # http://rubyforge.org/pipermail/mongrel-users/2007-July/003747.html
11   def pull
12     _sha1_flash_self
13   end
15   def index
16   end
18   # used by mup-compatible upload progress
19   def status
20     tmp = $upr.read(params[:upload_id]).inspect
21     render :text => "#{Rack::Utils.escape_html(tmp)}\n"
22   end
24   # used by mup-compatible upload progress
25   def progress
26     render :update do |page|
27       status = $upr.read(params[:upload_id]) and
28          page.upload_progress.update(status.length, status.seen)
29     end
30   end
32   # used by mup-compatible upload progress
33   def upload
34     size, hexdigest = _read_sha1_size
35     render :text => "sha1: #{hexdigest}<br />" \
36                     "size: #{size}<br />" \
37                     '<script type="text/javascript">' \
38                     'window.parent.UploadProgress.finish();</script>'
39   end
41 private
43   def _read_sha1_size
44     file = params[:data] or return [ -1, :unknown ]
45     File.unlink(file.path) if file.respond_to?(:path)
46     digest = Digest::SHA1.new
47     if buf = file.read(16384)
48       begin
49         digest.update(buf)
50       end while file.read(16384, buf)
51     end
52     [ file.size, digest.hexdigest ]
53   end
55   def _sha1_flash_self
56     if request.post?
57       size, hexdigest = _read_sha1_size
58       msg = "Successfully upload file (size: #{size}, sha1: #{hexdigest})"
59       flash[:notice] = msg
60       redirect_to :action => params[:action]
61     end
62   end
64 end