我正在尝试上传rails中的文件
我创建了一个包含以下代码的模型
def self.save(upload,id)
name = upload[:img].original_filename
directory = "public/user_db"
# create the file path
path = File.join(directory, id)
# write the file
File.open(path, "wb") { |f| f.write(upload['img'].read) }
end
end
我的观点有以下字段。
<div class="field">
<input type="file" name="img" id="img" placeholder="upload your DP" />
</div>
我的控制器正在调用保存功能,如下所示 :
post = DataFile.save(params,@fbuser.id)
答案 0 :(得分:3)
<强> Carrierwave 强> https://github.com/carrierwaveuploader/carrierwave
<强>回形针强> https://github.com/thoughtbot/paperclip
<强>蜻蜓强> https://github.com/markevans/dragonfly
只需按照安装说明进行操作,迁移数据库,告诉模型如何表现,并在5分钟内完成所有头痛: - )
关于您的问题 -
name = upload[:img].original_filename
这引发了一次考试,因为upload[:img]
只包含一个字符串。所以不需要.original_filename
但是再次 - 请使用其中一个宝石(或者只是阅读代码以了解如何操作)。那里还有Railscasts http://railscasts.com/episodes/253-carrierwave-file-uploads 和http://railscasts.com/episodes/134-paperclip https://www.youtube.com/watch?v=gp_kn6afl-Y
欢呼声
答案 1 :(得分:1)
A只有标签在视图中并且非常开始工作:)感谢您的帮助。该行正在关注
<%= f.file_field "img" %>
并在控制器中
post = DataFile.save(params[:fbuser],@fbuser.id.to_s)