Skip to content

Instantly share code, notes, and snippets.

@tetu1225
Created July 18, 2011 06:00
Show Gist options
  • Save tetu1225/1088643 to your computer and use it in GitHub Desktop.
Save tetu1225/1088643 to your computer and use it in GitHub Desktop.
Sinatraで画像ファイルをアップロードして表示する
require 'sinatra'
require 'haml'
# 静的コンテンツ参照のためのパス設定
set :public, File.dirname(__FILE__) + '/public'
# アップロード
get '/' do
haml :index
end
# アップロード処理
post '/upload' do
if params[:file]
save_path = "./public/images/#{params[:file][:filename]}"
File.open(save_path, 'wb') do |f|
p params[:file][:tempfile]
f.write params[:file][:tempfile].read
@mes = "アップロード成功"
end
else
@mes = "アップロード失敗"
end
haml :upload
redirect 'images'
end
# アップロードした画像の表示
get '/images' do
images_name = Dir.glob("public/images/*")
@images_path = []
images_name.each do |image|
@images_path << image.gsub("public/", "./")
end
haml :images
end
!!!html5
%html
%body
- @images_path.each do |image_path|
%img{:src => image_path}
!!!html5
%html
%body
%form{:action => "./upload", :method => "post", :enctype => "multipart/form-data"}
%input{:type => "file", :name => "file"}
%input{:type => "submit", :name => "submit"}
!!!html5
%html
%body
%p= @mes
@tetu1225
Copy link
Author

静的コンテンツに関しては以下が参考になった。
http://d.hatena.ne.jp/seiunsky/20090728/1248805790

@tetu1225
Copy link
Author

ディレクトリ構成は以下。
app_root
 └app.rb
 └public
  └images
 └views
  └images.haml
  └index.haml
  └upload.haml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment