1.Views
1)使用form_tag生成表单
<%= form_tag({action: :upload}, multipart: true) do %>
<%= file_field_tag 'picture' %>
<% end %>
2)使用form_for
<%= form_for @person do |f| %>
<%= f.file_field :picture %>
<% end %>
2.在model上写业务逻辑处理
class MyFile < ActiveRecord::Base
def file=(file_field) # 这是有特殊含义的
#注意使用wb+方法
File.open("#{RAILS_ROOT}/myfile", "wb+") do |f|
f.write(file_field.read)
end
end
end
3.controller处理
class UploadController < ApplicationController
def upload
unless request.get?
file = MyFile.new(params[:file]) # 自动调用 File 里面的file=method
if file.save
redirect_to path, notice: {}
else
# 失败的操作
end
end
end
end
4.Controller(选用)
def upload
uploaded_io = params[:person][:picture] #通过params获取文件
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
网友评论