Last active
December 14, 2015 13:17
-
-
Save holysugar/e1e1f88ba32ffa4812ac to your computer and use it in GitHub Desktop.
Sinatra から Google Drive への雑なアップロードサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'https://rubygems.org' | |
gem 'dotenv' | |
gem 'google_drive', github: 'holysugar/google-drive-ruby', branch: 'upload-in-collection' | |
gem 'sinatra' | |
gem 'haml' | |
gem 'pry' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
require 'haml' | |
require 'google_drive' | |
def drive_session | |
@drive_session ||= GoogleDrive.saved_session("config.json") | |
end | |
def collection | |
# サンプルって名前のフォルダを作っておく(あるいはIDで取得して file_by_id) | |
drive_session.collection_by_title("サンプル") | |
# drive_session.file_by_id(ENV['DRIVE_FOLDER_ID']) | |
end | |
# アクセストークンの取得 | |
if !File.exist?("config.json") && (ENV['GOOGLE_CLIENT_ID'] || ENV['REFRESH_TOKEN']) | |
if ENV['REFRESH_TOKEN'] | |
hash = { "refresh_token": ENV['REFRESH_TOKEN'] } | |
else | |
hash = { | |
"client_id": ENV['GOOGLE_CLIENT_ID'], | |
"client_secret": ENV['GOOGLE_CLIENT_SECRET'], | |
} | |
end | |
File.write("config.json", hash.to_json) | |
end | |
drive_session | |
get '/' do | |
@filelist = collection.files | |
haml :index | |
end | |
post '/upload' do | |
if params[:file] | |
name = params[:name] || "名無しさん" | |
filename = "#{name}_#{params[:file][:filename]}" | |
drive_session.upload_from_io(params[:file][:tempfile], filename, convert: false, parents: collection) | |
@message = 'アップロード成功' | |
else | |
@message = 'アップロード失敗' | |
end | |
redirect "/" | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!!!html5 | |
%html | |
%body | |
%p= @message | |
%form{:action => "./upload", :method => "post", :enctype => "multipart/form-data"} | |
%input{:type => "text", :name => "name", :value => "でふぉるとなまえ"} | |
%input{:type => "file", :name => "file"} | |
%input{:type => "submit", :name => "submit"} | |
%h2 filelist | |
%ul | |
- @filelist.each do |file| | |
%li&= file.title |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment