首页 文章

使用Cloudinary和Carrierwave直接上传

提问于
浏览
1

我一直在按照Cloudinary提供的说明进行操作,但无法直接上传 . 为了进一步复杂化,我的图像上传是一个多态类,通常是嵌套的形式 .

我正在使用Cloudinary和Carrierwave宝石 . 在非直接设置中,一切正常,但是如果一次上传的图像太多,则独角兽会超时(可能经常出现这种情况)

下面是添加文件上传的部分内容 . 它嵌套在多种不同的表单中,用户可以动态添加和删除字段 . 根据说明,我尝试用 = cl_image_upload :asset 替换 = f.file_field :asset= f.hidden_field :asset_cache ,但是,这会引发错误: wrong number of arguments (1 for 2..3) . 添加第二个参数时,它会附加到生成的HTML中的 data-cloudinary-field . 此外,添加图像时没有上传,也没有附加到记录的引用 .

_image_fields.html.haml

.image-field-group
  .field
    = f.label :asset, "Image"
    = cl_image_upload :asset
    / = f.file_field :asset
    / = f.hidden_field :asset_cache

  - if f.object && f.object.asset && f.object.asset.filename
    .image-box
      = cl_image_tag(f.object.asset.filename.to_s, :transformation => 'hint', alt: f.object.asset.filename.to_s)

  .remove-fields
    = link_to_remove_fields f

以下是相关文件:

image.rb

class Image < ActiveRecord::Base
  default_scope order('images.id ASC')

  attr_accessible               :asset,
                                :asset_cache

  belongs_to                    :imageable, polymorphic: true

  mount_uploader                :asset, ImageUploader
end

image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

编辑:添加图像控制器

images_controller.rb

class ImagesController < ApplicationController
  before_filter :load_imageable

  def index
    @images = @imageable.images
  end

  def new
    @image = @imageable.images.new
  end

  def create
    @image = @imageable.images.new(params[:image])
    if @image.save
      redirect_to @imageable, notice: "Image created."
    else
      render :new
    end
  end

private

  def load_imageable
    resource, id = request.path.split('/')[1, 2]
    @imageable = resource.singularize.classify.constantize.find(id)
  end
end

1 回答

  • 1

    以下文档部分介绍了如何在Ruby on Rails应用程序中使用浏览器中的直接图像上载 . 确保以正确的顺序包含jQuery和所需的插件,并添加所需的Javascript配置 .

    http://cloudinary.com/documentation/rails_image_upload#direct_uploading_from_the_browser

    嵌入执行直接图像上载的文件输入字段是使用接受输入字段名称的 cl_image_upload_tag 辅助方法完成的 .

    使用CarrierWave时,可以使用 cl_image_upload 辅助方法 . 直接调用此方法时,需要传递对象名称和属性(与其他Rails视图辅助方法一样,例如 text_field_tagtext_field ) . 或者,您可以将它与Rails的标准表单构建器一起使用 . 假设您的模型名为 entity 且您的CarrierWaver上传器的属性名为 asset ,则以下视图代码应嵌入一个签名文件输入字段,以便从浏览器直接上传:

    = form_for(:entity) do |f|
      = f.cl_image_upload(:asset)
    

    此外,如下所示,您可以使用 present? 检查资产是否存在,并将CarrierWave属性直接传递给 cl_image_tag . 或者,您可以使用CarrierWave标准版本,而不是使用 cl_image_tag 动态构建图像URL .

    - if f.object && f.object.asset.present?
      .image-box
        = cl_image_tag(f.object.asset, :transformation => 'hint', alt: f.object.asset.filename.to_s)
    

    如果文件输入字段已成功添加到您的视图但未执行直接上载,则应验证控制台中是否存在Javascript错误,并且所有jQuery插件都已正确包含 .

相关问题