0

似乎无法确定为什么我会得到一个未定义的方法 original_filename,试图进行文件上传以检查文件扩展名。我在这里出错的任何想法

class SpreadsheetTagService 
  include Roo

  def initialize(uploaded_file)
    open_spreadsheet(File.new(uploaded_file.tempfile.path))
    read_file(open_spreadsheet)
  end 

  private 
    def read_file(file)
      @spreadsheet = open_spreadsheet(file)

      @spreadsheet.each_with_pagename do |name,sheet|    
        Rails.logger.debug( sheet )
      end    
    end

    def open_spreadsheet(file)
      case File.extname(file.path)
        when ".csv" then Csv.new(file.path, nil, :ignore)
        when ".xls" then Excel.new(file.path, nil, :ignore)
        when ".xlsx" then Excelx.new(file.path, nil, :ignore)
        else raise "Unknown file type: #{file.original_filename}"
      end
    end
end

控制器

class SpreadsheetServiceController < ApplicationController

  def new
  end

  def create    
    parser = SpreadsheetTagService.new(params[:spreadsheet][:file])

    respond_to do |format|
      format.all {render :json => 'Done'}
    end
  end
end 
4

1 回答 1

0

这对我有用,删除了#{file.original_filename}from raise 异常,修改了代码,以便正确保存文件扩展名:

class SpreadsheetTagService
  include Roo

  def initialize(uploaded_file)
    ext = File.extname(uploaded_file.original_filename)
    @tmp_destination = "#{Rails.root}/tmp/tag-import#{ext}"
    @file_path = save_file_to_tmp(uploaded_file)
    @file = File.new(@file_path)
    read_file(@file)
  end

  private
  def save_file_to_tmp(uploaded_file)
    FileUtils.mv(uploaded_file.tempfile, @tmp_destination )
    @tmp_destination
  end

  def read_file(file)
    @spreadsheet = open_spreadsheet(file)
    @spreadsheet.each_with_pagename do |name,sheet|
      Rails.logger.debug( sheet )
    end
  end

  def open_spreadsheet(file)
    case File.extname(file.path)
    when ".csv" then Csv.new(file.path, nil, :ignore)
    when ".xls" then Excel.new(file.path, nil, :ignore)
    when ".xlsx" then Excelx.new(file.path, nil, :ignore)
    else raise "Unknown file type"
    end
  end
end
于 2013-08-01T18:25:12.333 回答