首页 > 解决方案 > 带有多个文件的 Rails file_field_tag 向控制器提供随机字符串

问题描述

我正在构建一个表格来接受多个图像。这是 Slim 中的表格

  = form_tag(product_images_path(product_id: product.id), multipart: true, remote: true) do
    label Add Image
    = file_field_tag(:attachment, multiple: true, name: 'image[attachment]', direct_upload: true, class: 'drop-target')
    = submit_tag 'Upload'

当我测试这个表单并附加一个文件并且数据到达控制器时,附件变成了某种随机字符串,而不是ActionDispatch::Http::UploadedFile我期望的数组。params这是在控制台中检查的结果:

<ActionController::Parameters {
  "utf8"=>"✓",
  "authenticity_token"=>"....", 
  "image"=>{"attachment"=>"eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBOQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--79ca56f5342586a657d079d36e45f769dacc9356"},
  "commit"=>"Upload", 
  "controller"=>"rics_channels/admin/images", 
  "action"=>"create", 
  "product_id"=>"5355"} 
permitted: false>

我不知道如何正确格式化/处理image[attachment]'s. 看到我做错了什么吗?

标签: ruby-on-railsrails-activestorage

解决方案


您正在使用直接上传(请注意direct_upload: true传递给file_field_tag)。提交表单后,Active Storage 的 JavaScript 会绕过您的应用程序将文件直接上传到您的存储服务。代替实际文件,应用程序接收签名的 blob ID。

您可以将此签名的 blob ID 传递给attach(这里我假设file是您的附件的名称):

image.file.attach(params[:image][:attachment])

…或者用它来实例化一条新记录:

image = Image.new(file: params[:image][:attachment])

Active Storage 使用签名的 blob ID 来查找相应的 blob 并将其附加到您的记录中。


推荐阅读