Rails CarrierWave 上传的问题!

nuanshuidai · August 20, 2017 · Last by nuanshuidai replied at August 21, 2017 · 1606 hits

利用 CarrierWave 上传一些图片,需要同时多张上传。这些图片和表字段无关,就单纯的传文件到服务器,看了 CarrierWave 的接口,类似这样:

controller 里:

def mystore
    up_file = params[:localfile]
    myfile = MyuploaderUploader.new
    myfile.store!(up_file)
end

试着写了个小 DEMO,代码如下:

view 里:

<%= form_for @cang_image do |f| %>
<%= f.label :名称: %>
<%= f.text_field :cang_image_name, class: 'form-control' %>
<%= f.label :图例 %>
<%= f.file_field :image ,class: 'form-control',multiple: true %>
<%#= f.hidden_field :image_cache %>
<%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %>

controller 里的方法:

def create
       @image = cang_image_params["image"]
        myfile = CangImageUploader.new        
        myfile.store!(@image)
end 

运行时报这样的错:

有二个问题: 1:不知怎么解决。 2:store!(@image) 里的参数有啥具体要求不是很清楚。

有懂的同学指教下!谢谢!

model 需要 mount 吧,检查下看吧。

问题 1,请再仔细阅读 Getting Started(https://github.com/carrierwaveuploader/carrierwave#getting-started),检查每个步骤。

问题 2,从 源码可以看出store!方法的参数可以是 nil,也可以是 any kind of file object

Reply to chenge

mount 是用在绑定到 model 上某个字段属性上才用的。我这里是不需要 model,只是单纯的将 params 里传过来的 image 内容利用 carrierwave 保存在指定的目录里而已啊!

Reply to qqerqqer

利用健壮函数从 params 里取出 image,也就是传过来的文件,看出错是类型不匹配,可 carrierwave 官方文档里也是从 params 参数里取值啊!不太明白怎么拆解 params 参数了。

Reply to nuanshuidai

下个断点,看看你的@test的内容什么

Reply to qqerqqer

解决了: @image = cang_image_params["image"][0] 代码的最后加个 [0] 就 OK 了,应该还是对象匹配问题。

nuanshuidai closed this topic. 21 Aug 09:02
nuanshuidai reopened this topic. 21 Aug 09:02
You need to Sign in before reply, if you don't have an account, please Sign up first.