デシベル/移行/20110711000004_create_files.rb
class CreateFiles < ActiveRecord::Migration
def change
create_table :files do |t|
t.string :name
# If using MySQL, blobs default to 64k, so we have to give
# an explicit size to extend them
t.binary :data, :limit => 1.megabyte
end
end
end
アプリ/コントローラー/upload_controller.rb
class UploadController < ApplicationController
def get
@file = File.new
end
end
アプリ/ビュー/アップロード/get.html.erb
<% form_for(:file,
url: {action: 'save'},
html: {multipart: true}) do |form| %>
Upload your file: <%= form.file_field("uploaded_file") %><br/>
<%= submit_tag("Upload file") %>
<% end %>
アプリ/モデル/file.rb
class File < ActiveRecord::Base
def uploaded_file=(file_field)
self.name = base_part_of(file_field.original_filename)
self.data = file_field.read
end
def base_part_of(file_name)
File.basename(file_name).gsub(/[^\w._-]/, '')
end
end
アプリ/コントローラー/upload_controller.rb
def save
@file = File.new(params[:file])
if @file.save
redirect_to(action: 'show', id: @file.id)
else
render(action: :get)
end
end
アプリ/コントローラー/upload_controller.rb
def file
@file = File.find(params[:id])
send_data(@File.data,
filename: @File.name,
disposition: "inline")
end
アプリ/コントローラー/upload_controller.rb
def show
@file = File.find(params[:id])
end
アプリ/ビュー/アップロード/show.html.erb
<h3><%= @file.name %></h3>
<img src="<%= url_for(:action => 'file', :id => @file.id) %>"/>