-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdropbox_controller.rb
57 lines (46 loc) · 2.41 KB
/
dropbox_controller.rb
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
require 'dropbox_sdk'
# This is an example of a Rails 3 controller that authorizes an application
# and then uploads a file to the user's Dropbox.
# You must set these
APP_KEY = ""
APP_SECRET = ""
ACCESS_TYPE = :app_folder #The two valid values here are :app_folder and :dropbox
#The default is :app_folder, but your application might be
#set to have full :dropbox access. Check your app at
#https://www.dropbox.com/developers/apps
# Examples routes for config/routes.rb (Rails 3)
#match 'db/authorize', :controller => 'db', :action => 'authorize'
#match 'db/upload', :controller => 'db', :action => 'upload'
class DbController < ApplicationController
def authorize
if not params[:oauth_token] then
dbsession = DropboxSession.new(APP_KEY, APP_SECRET)
session[:dropbox_session] = dbsession.serialize #serialize and save this DropboxSession
#pass to get_authorize_url a callback url that will return the user here
redirect_to dbsession.get_authorize_url url_for(:action => 'authorize')
else
# the user has returned from Dropbox
dbsession = DropboxSession.deserialize(session[:dropbox_session])
dbsession.get_access_token #we've been authorized, so now request an access_token
session[:dropbox_session] = dbsession.serialize
redirect_to :action => 'upload'
end
end
def upload
# Check if user has no dropbox session...re-direct them to authorize
return redirect_to(:action => 'authorize') unless session[:dropbox_session]
dbsession = DropboxSession.deserialize(session[:dropbox_session])
client = DropboxClient.new(dbsession, ACCESS_TYPE) #raise an exception if session not authorized
info = client.account_info # look up account information
if request.method != "POST"
# show a file upload page
render :inline =>
"#{info['email']} <br/><%= form_tag({:action => :upload}, :multipart => true) do %><%= file_field_tag 'file' %><%= submit_tag %><% end %>"
return
else
# upload the posted file to dropbox keeping the same name
resp = client.put_file(params[:file].original_filename, params[:file].read)
render :text => "Upload successful! File now at #{resp['path']}"
end
end
end