Rails 5.2选择图片后如何通过Carrierwave自动上传图片

时间:2018-08-11 14:58:33

标签: ruby-on-rails ruby-on-rails-5 carrierwave

我用Carrierwave将图像上传到多态表。

使用以下代码,我可以正确上传和显示图像。

但是现在我想在new.html.erb中选择图像后自动上传并显示图像。换句话说,我要跑步

Attachment.create(:attachment => params[:attachment], :attachmentable =>@img) if params[:attachment]

在执行img create 操作之前,紧接在我选择图像之后。

我应该如何处理代码?非常感谢您为我提供指导。

我的部分代码如下:

我的Gemfiles

gem 'rails', '~> 5.2'
gem 'carrierwave', '~> 1.2', '>= 1.2.2'
gem 'mini_magick'

我的img.rb

class Img < ActiveRecord::Base
  has_many :attachments, as: :attachmentable, :dependent => :destroy
end

我的attachment.rb模型:

class Attachment < ApplicationRecord
  mount_uploader :attachment, ImageUploader
  belongs_to :attachmentable, :polymorphic => true
end

我的imgs_controller的管理员

class ImgsController < ApplicationController

  def index
    @imgs = Img.all
  end

  def show
    @img = Img.find(params[:id])
  end

  def new
    @img = Img.new
  end

  def create
    @img = Img.new(img_params)
    if @img.save
      Attachment.create(:attachment => params[:attachment], :attachmentable =>@img) if params[:attachment]
      redirect_to @img
    end
  end

  def destroy
    @img = Img.find(params[:id])
    @img.destroy
    redirect_to @img
  end

  private

  def img_params
    params.require(:img).permit(:img_name)
  end
end

我的img HTML

# new.html.erb

<%= form_for(@img,:html => {:multipart => true}) do |f| %>
  <%= f.text_field :img_name %>
  <%= file_field_tag :attachment %>
  <%= f.submit "upload" %>
<% end %>



# show.html.erb

<% @img.attachments.each do |f| %>
  <%= image_tag f.attachment.url %>
<% end %>

1 个答案:

答案 0 :(得分:0)

根据帖子中提到的描述,您希望用户从您所在的位置浏览图像后,立即使用载波将图像上传到云存储中。

一种方法是在用户完成从系统中浏览图像并将该图像远程上传到云之后,对控制器进行ajax调用。

不必要:

但是,如果用户在浏览过程中不断更改图像会发生什么,那么无论您不显示该图像还是需要该图像,您都将上传已浏览的每个图像。

解决方法:

您可以使用jquery读取浏览的图像,然后根据需要将图像显示给用户;提交表单后,只有将图像上传到云存储中。