Created
July 18, 2011 06:00
Sinatraで画像ファイルをアップロードして表示する
This file contains hidden or 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' | |
# 静的コンテンツ参照のためのパス設定 | |
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 |
This file contains hidden or 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 | |
- @images_path.each do |image_path| | |
%img{:src => image_path} |
This file contains hidden or 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 | |
%form{:action => "./upload", :method => "post", :enctype => "multipart/form-data"} | |
%input{:type => "file", :name => "file"} | |
%input{:type => "submit", :name => "submit"} |
This file contains hidden or 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= @mes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ディレクトリ構成は以下。
app_root
└app.rb
└public
└images
└views
└images.haml
└index.haml
└upload.haml