udi*_*dit 2 ruby file-upload ruby-on-rails file
所以我试图实现文件上传功能,当用户上传文件时,我可以将其读入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
Run Code Online (Sandbox Code Playgroud)
当我尝试读取文件时,它会在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6182 次 |
| 最近记录: |