我一直在Cloudinary文档中寻找一段时间,但无法弄清楚如何使用Rails和html表单向其上传多个文件。
我为我的Carrierwave添加了Cloudinary支持ImageUploader
include Cloudinary::CarrierWave
我将我的api-key和秘密添加到config/cloudinary.yml
但我还需要改变什么?就目前而言,我保留了与载波相关的所有内容。所以我的表单包含一个文件字段
<%=file_field_tag "images[]", type: :file, multiple: true %>
然后为每个图像创建一个新的picture
实例,并且每个图片实例都包含:image
属性
if params[:images]
params[:images].each do |image|
@post.pictures.create(image: image)
end
end
我保持ImageUploader
或多或少的默认值。
class ImageUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
当我上传一些图片时,网址链接到一个云页面,但实际上没有任何内容上传到cloudinary。我可以在create
控制器的picture
操作中添加一些内容来实际上传图像吗?像
def create
@picture = Picture.new(picture_params)
@picture.save
Cloudinary::Uploader.upload(picture_params)
end
答案 0 :(得分:0)
根据image
的值,您可以这样做:
if params[:images]
params[:images].each do |image|
@post.pictures.create(image: image)
end
upload_images(@post.pictures)
end
def upload_images(images)
images.each do |i|
Cloudinary::Uploader.upload(i)
end
end
答案 1 :(得分:0)
这是在Paperclip中完成的。
class Attachment < ApplicationRecord
if Rails.env == 'production'
has_attached_file :file, :storage => :cloudinary, :path => ':class/:id/:filename', :cloudinary_resource_type => :raw
class Deal < ApplicationRecord
has_and_belongs_to_many :attachments, dependent: :destroy
accepts_nested_attributes_for :images, :attachments, reject_if: :all_blank, allow_destroy: true
def files=(files)
files.each do |file|
attachments.build(file: file)
end
end
#controller
def deal_params
params.require(:deal).permit :name, ..., photos: [], files: []
#view
= form_for([parent, child], html: { multipart: true }) do |f|
=f.file_field :files, multiple: true, class: 'form-control'