gpt4 book ai didi

ruby-on-rails - 在 Controller 方法中将上传的文件读入文件对象 -"can' t 将 Tempfile 转换为字符串"

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:21 25 4
gpt4 key购买 nike

所以我尝试实现文件上传功能,当用户上传文件时,我可以将其读入 File 对象并进行相应处理:

def create
name = params[:upload]['datafile'].original_filename
directory = "public/data"

# create the file path
path = File.join(directory, name)

# read the file
File.open(params[:upload][:datafile], 'rb') { | file |
# do something to the file
}
end

当我尝试读取文件时,它会在 File.open 上抛出“无法将 Tempfile 转换为字符串”错误。

我错过了什么?

最佳答案

这意味着 params[:upload][:datafile] 已经是一个文件,所以你不需要将它交给 File.open。你的代码应该是:

def create
name = params[:upload]['datafile'].original_filename
directory = "public/data"

# create the file path
path = File.join(directory, name)

file = params[:upload][:datafile]
# do something to the file, for example:
# file.read(2) #=> "ab"
end

关于ruby-on-rails - 在 Controller 方法中将上传的文件读入文件对象 -"can' t 将 Tempfile 转换为字符串",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3278177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com