我正在构建一个接受多个图像的表格。这是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]
。看到我做错了什么吗?
答案 0 :(得分:1)
您正在使用直接上传(请注意,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,并将其附加到您的记录中。
答案 1 :(得分:0)
我发现问题是我的file_field_tag
的名字需要额外的[]
。
= file_field_tag('attachment[images][]', multiple: true, class: 'drop-target')
然后在控制器中:
params[:attachment][:images]
#=>[#<ActionDispatch::Http::UploadedFile:0x00007f8a70185a90
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"attachment[images][]\"; filename=\"image1.jpg\"\r\nContent-Type: image/jpeg\r\n",
@original_filename="image.jpg",
@tempfile=#<File:/var/folders/p6/dshxxfqj6lq83t652t6j59ym0000gn/T/RackMultipart20180703-9499-9rs1km.jpg>>,
#<ActionDispatch::Http::UploadedFile:0x00007f8a70a0bac0
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"attachment[images][]\"; filename=\"image2.jpg\"\r\nContent-Type: image/jpeg\r\n",
@original_filename="image2.jpg",
@tempfile=#<File:/var/folders/p6/dshxxfqj6lq83t652t6j59ym0000gn/T/RackMultipart20180703-9499-wfuqs.jpg>>,
#<ActionDispatch::Http::UploadedFile:0x00007f8a6dc82338
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"attachment[images][]\"; filename=\"image3.jpg\"\r\nContent-Type: image/jpeg\r\n",
@original_filename="image.jpg",
@tempfile=#<File:/var/folders/p6/dshxxfqj6lq83t652t6j59ym0000gn/T/RackMultipart20180703-9499-9oe8y4.jpg>>]