我有一个
形式的文本文件texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
>>>>
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
>>>>
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext
etc
我想将它与>>>>一起分开,并将其余内容保存到Rails模型中,无需将文件保存在服务器上。我知道我的解析器有效,但我很难搞清楚如何解析文件而不将其保存到服务器。我试过在params [:file]对象上调用.read,但它抛出一个异常,说它没有那个方法。如果可能的话,我宁愿避免回形针和载波。任何人都可以提供一些关于如何访问文本的示例代码,而无需保存它吗?
编辑:我尝试的代码来自此堆栈交换问题How to upload a text file and parse contents into database in RoR
uploaded_io = params[:file_upload]
file_contents = uploaded_io.read
file_contents.each_line do |f|
...
end
答案 0 :(得分:1)
当您上传文件时,Rails将在tmp
目录中创建一个文件,稍后将自动删除该文件。因此,您无需执行任何操作即可自动删除上传内容。这意味着如果您想保留文件,则需要手动将其复制到永久位置。
您可以通过调用tempfile
上的params[:file_upload]
方法来访问临时文件,例如:
class UploadController < ApplicationController
def new
# upload form
end
def create
data = params[:file_upload].tempfile.read
parts = data.split(">>>>\n")
# do something with parts
end
end
答案 1 :(得分:0)
file_io = params[:file]
stream = file_io.read
应该可以正常工作,但请确保您的表单设置正确,并且您正在调用正确的params对象。另请尝试将multipart: true
添加到表单选项中。我之前遇到过类似的问题,实际上文件上传没有被正确使用。
您也可以检查file_io.original_filename
的params [:file] - 即使您的读取不起作用,您仍然可以访问文件名。如果这也不起作用,问题很可能是其他问题(可能是表单构建器)。