upr.git  about / heads / tags
Upload Progress for Rack
blob bd4fc61819213369a9c07f818cba2ae6ae65bd39 1603 bytes (raw)
$ git show HEAD:examples/rails_app-2.3.4/app/controllers/files_controller.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
 
require 'digest/sha1'

class FilesController < ApplicationController
  # used by jQuery streaming upload progress
  def new
    _sha1_flash_self
  end

  # based on ry dahl's streaming AJAX pull:
  # http://rubyforge.org/pipermail/mongrel-users/2007-July/003747.html
  def pull
    _sha1_flash_self
  end

  def index
  end

  # used by mup-compatible upload progress
  def status
    tmp = $upr.read(params[:upload_id]).inspect
    render :text => "#{Rack::Utils.escape_html(tmp)}\n"
  end

  # used by mup-compatible upload progress
  def progress
    render :update do |page|
      status = $upr.read(params[:upload_id]) and
         page.upload_progress.update(status.length, status.seen)
    end
  end

  # used by mup-compatible upload progress
  def upload
    size, hexdigest = _read_sha1_size
    render :text => "sha1: #{hexdigest}<br />" \
                    "size: #{size}<br />" \
                    '<script type="text/javascript">' \
                    'window.parent.UploadProgress.finish();</script>'
  end

private

  def _read_sha1_size
    file = params[:data] or return [ -1, :unknown ]
    File.unlink(file.path) if file.respond_to?(:path)
    digest = Digest::SHA1.new
    if buf = file.read(16384)
      begin
        digest.update(buf)
      end while file.read(16384, buf)
    end
    [ file.size, digest.hexdigest ]
  end

  def _sha1_flash_self
    if request.post?
      size, hexdigest = _read_sha1_size
      msg = "Successfully upload file (size: #{size}, sha1: #{hexdigest})"
      flash[:notice] = msg
      redirect_to :action => params[:action]
    end
  end

end

git clone https://yhbt.net/upr.git