在我的lib / csv_validation.rb文件中,我得到了我的验证方法:
def self.validate(file, delimiter, columns)
return false unless File.exist?(file)
content = File.read(file, encoding: 'utf-8')
return false unless content.valid_encoding?
content.each_line do |line|
return false if line.count(delimiter) < columns - 1
end
true
end
当我通过ajax post请求发送CSV文件时,我收到以下错误:
Started POST "/students/import" for 127.0.0.1 at 2017-12-20 01:03:43 +0100
Processing by StudentsController#import as */*
Parameters: {"file"=>#<ActionDispatch::Http::UploadedFile:0x007fd0a228ca38 @tempfile=#<Tempfile:/tmp/RackMultipart20171220-4516-or6qi3.csv>, @original_filename="students_fail.csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"students_fail.csv\"\r\nContent-Type: text/csv\r\n">}
Completed 500 Internal Server Error in 19ms (ActiveRecord: 0.0ms)
TypeError (can't convert ActionDispatch::Http::UploadedFile to IO (ActionDispatch::Http::UploadedFile#to_io gives Tempfile)):
app/models/student.rb:114:in `exist?'
app/models/student.rb:114:in `import'
app/controllers/students_controller.rb:50:in `import'
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.text.erb (0.4ms)
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.4ms)
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.6ms)
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (14.4ms)
DEPRECATION WARNING: Accessing mime types via constants is deprecated. Please change `Mime::HTML` to `Mime[:html]`. (called from acceptable_content_type? at /var/lib/gems/2.4.0/gems/web-console-2.3.0/lib/web_console/middleware.rb:58)
我在寻找can't convert ActionDispatch::Http::UploadedFile to IO
,但我发现像can't convert ActionDispatch::Http::UploadedFile into String
这样的东西。
我不知道如何处理此错误或我找到有相同问题的人。
抱歉,我的英语不好,请求帮忙。
你会想要使用ActionDispatch::Http::UploadedFile#tempfile
方法。
记录的here。
所以你可以这样称呼它:
File.read(file.tempfile, encoding: 'utf-8')
这将允许对象转换为实际文件而不是ActionDispatch
对象。