【问题标题】:Carrierwave, Dropzone.js Rails 4, Strong parametersCarrierwave,Dropzone.js Rails 4,强参数
【发布时间】:2014-05-24 13:14:26
【问题描述】:

我正在尝试使用 Carrierwave 和 Dropzone.js 上传多张图片,但是当我提交表单时出现以下错误。

请注意,没有 dropzone.js 的相同表单可以正常工作,这意味着当我只是使用 HTML5 上传多个图像时。

请查看下面我提交表单时创建的哈希(通过 ajax 使用 dropzone)


"project_images_attributes"=>[{"image"=

[#, @original_filename="artist4.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"project[project_ images_attributes][][image][]\"; filename=\"artist4.jpg\"\r\nContent-Type: image/jpeg\r\n">, #, @original_filename="feed1.jpg", @骗局 tent_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"project[project_images_attributes][][image][]\"; filename=\"feed1.jpg\"\ r\nContent-Type: image/jpeg\r\n">, #, @original_filename="gallery1.jpg", @content_type="image/jpeg", @headers="Content-Disposition: 表格数据; name=\"项目[project_images_attributes][][image][]\"; filename=\"gallery1.jpg\"\r\nContent-Type: image/jpeg\r\n">]}]}, "project-vide o"=>[""], "commit"=>"创建项目"}

不允许的参数:图片

请注意,我已将控制器中的图像参数列入白名单,并且它使用 HTML 5 工作,但不使用 ajax 和 dropzone.js

有谁知道如何解决这个问题?

谢谢

【问题讨论】:

  • 从您已将属性列入白名单的控制器共享相关代码。

标签: ruby-on-rails-4 carrierwave strong-parameters dropzone.js


【解决方案1】:

用于上下文化我最终结果的代码:

  private
  def pin_image_params
    #params.require(:pin_image).permit(:photo) (not permitted)
    #params.require(:pin_image).permit(photo: [:'0']) (permitted but action handler error)
    #params.require(:pin_image)["photo"].values.first (stringify_keys error)
    params.require(:photos).values
  end

强大的参数不断返回未经许可的参数:照片。在控制台中查看,我看到参数正在编号,我可以访问它们的唯一方法是按编号潜入。尽管如此,尝试将它们直接传递给create 还是返回了错误。这是因为模型无法理解编号哈希的格式。知道它需要遍历每个附加图像还不够聪明。所以:

def create
   # so pin_image_params is an array of files basically
   @pin_images = pin_image_params.inject([]) do |memo, photo|
   # this pattern will store the memo into the @pin_images reference
      memo << PinImage.create(photo: photo)
   # keying it explicitly
   end
   if @pin_images.present?
      render json: { id: @pin_images.map(&:id) }, :status => 200
   else
      #  you need to send an error header, otherwise Dropzone
      #  will not interpret the response as an error:
      render json: { error: @pin_images.errors.full_messages.join(',')}, :status => 400
   end
end

我的控制器返回一个 id 列表,这些 id 被捕获在拥有 PinImage (Pin) 的模型的隐藏字段中。 (这是在通过 dropzone 提交 PinImages 的 ajax 的成功回调中完成的。)因此,当提交主模型时,我还必须处理在那里进行关联,但我发现我更喜欢通过nested_attributes_for 混淆。 YMMV。

【讨论】:

    【解决方案2】:

    查看您提交表单的方式。是form.submit吗?上传完成后,Dropzone 会自动通过 ajax 提交文件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多