仅将文件名作为字符串

时间:2015-08-31 06:25:05

标签: ruby-on-rails ruby-on-rails-3 model-view-controller file-upload

我正在尝试上传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)

但我收到此错误enter image description here

2 个答案:

答案 0 :(得分:3)

帮自己一个忙,不要重新发明轮子。在Rails中,有3个令人敬畏的宝石来处理文件上传,eatch有一个很棒的社区支持和大量的共享代码。

<强> 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-uploadshttp://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)