ruby on rails 实现文件的上传

把这段代码放入 Controller 里的 Application.rb

class ApplicationController < ActionController::Base
# Pick a unique cookie name to distinguish our session data from others'
session :session_key => '_upload_session_id'

def uploadFile(file)
if !file.original_filename.empty?
@filename=getFileName(file.original_filename)
File.open("#{RAILS_ROOT}/public/files/#{@filename}", "wb") do |f|
f.write(file.read)
end
return @filename
end
end

def getFileName(filename)
if !filename.nil?
return filename
end
end
end


Controller:
把这段代码放入 upload_controller中
class UploadController < ApplicationController
def upload
unless request.get?
if filename=uploadFile(params[:file]['file'])
end
end
end
end

View:
把这段代码放入 upload.rhtml 中
<%=start_form_tag ({:action=>"upload"},:multipart=>true )%>
<%= file_field("file", "file")%>
<input type="submit" />
<%=end_form_tag%>

这样就可以实现把文件上传到public/files目录中了

你可能感兴趣的:(F#,Ruby,Rails)