似乎无法确定为什么我会获取未定义的方法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
答案 0 :(得分:0)
这个对我有用,从引发异常中删除了#{file.original_filename}
,修改了代码以便正确保存文件扩展名:
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