以下两种form都可以上载文件(http://guides.rails.info/form_helpers.html#what-gets-uploaded)
第一种
<%= form_tag({:action => :upload}, :multipart => true) do %> <%= file_field_tag 'picture' %> <% end %>
第二种
<%= form_for @person do |f| %> <%= f.file_field :picture %> <% end %>
controller中
def upload uploaded_io = params[:person][:picture] File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file| file.write(uploaded_io.read) end end
实例:
涉及到xls读入并创建记录
view中
<%= form_for(@part, :url => {:action => "upload"}) do |f| %> <%= f.file_field :xls_file%> <%= f.submit %> <% end %
controller中
def upload begin if params[:part][:xls_file] uploaded_io = params[:part][:xls_file] workbook = Spreadsheet.open(uploaded_io.tempfile) sheet = workbook.worksheet 0 Part.transaction do sheet.each do |row| if row[0].is_a?(Float) part = Part.create!(:name=>row[1], :project_id => params[:part][:project_id], :size=>row[3], :material=>row[4], :quantity=>row[5].to_i, :weight=>row[6], :description=>row[8]) end end redirect_to ...... end else raise Errno::error #在没有选择导入文件直接点击上载时抛出一个异常 end rescue => err logger.error(err) redirect_to ...... end end
对上述controller中的处理增加出错提示、方便使用者定位自己的导入文件的错误
def upload part = Part.new begin if params[:part][:xls_file] uploaded_io = params[:part][:xls_file] workbook = Spreadsheet.open(uploaded_io.tempfile) sheet = workbook.worksheet 0 error_location = 0 #记录出错位置 Part.transaction do sheet.each do |row| error_location += 1 if row[7].is_a?(Float) chart = Chart.find_or_create_by_name(row[1]) category = Category.find_by_name(row[2]) part = Part.new( :project_id => params[:part][:project_id], :number => row[0], :chart_id => chart.id, :category_id => category.id, :name => row[3], :quantity => row[6].to_i, :weight => row[7].to_f, :description => row[9]) unless part.valid? raise part.errors.full_messages else part.save end end end redirect_to parts_path(:project_id => params[:part][:project_id]), :notice => I18n.t("flash.parts.upload_success.notice") end else raise "import empty!" end rescue => err #将出错信息记录到log中 logger.error("#{error_location} row Error!") logger.error(part.errors.full_messages) logger.error(err) #将错误信息显示到页面 if part.errors.blank? error_message = "没有选择导入文件!" else error_message = "导入失败!第#{error_location}行出错:" + part.errors.full_messages.to_s end redirect_to :back, :notice => error_message end endThe Spreadsheet Library:http://spreadsheet.rubyforge.org/GUIDE_txt.html