Railsでupload
mac$ rails new upload
mac$ cd upload/
mac$ bundle install
mac$ mkdir public/data
mac$ rails g model data_file name:string directory:string path:string
mac$ rails g controller upload
mac$ rake db:migrate
app/config/routes.rb
Upload::Application.routes.draw do get "upload" => "upload#index" post "uploadfile" => "upload#uploadfile" end
app/controllers/upload_controller.rb
class UploadController < ApplicationController def index render :file => '/upload/uploadfile.rhtml' end def uploadfile post = DataFile.save(params[:file]) render :text => "File has been uploaded successfully" end end
app/models/data_file.rb
class DataFile < ActiveRecord::Base def self.save(upload) name = upload.original_filename directory = "public/data" # create the file path path = File.join(directory, name) # write the file File.open(path, "wb") { |f| f.write(upload.read) } end end
app/views/upload/uploadfile.rhtml
<%= form_tag '/uploadfile', :multipart => true do %> <label for="file">File to Upload</label> <%= file_field_tag "file" %> <%= submit_tag %> <% end %>
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html