gem 'cocoon'

gem 'carrierwave'

gem 'mini_magick'

1.图片上传carrierwave配置,github

自己手动添加的配置,没用命令生成

在app下新建uploaders/enclosure_uploader.rb,内容如下

# encoding: utf-8

class EnclosureUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "enclosures/#{model.id}"  //存在public下,enclosures会自动创建
  end

  def cache_dir
    "#{Rails.root}/tmp/uploads"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :resize_to_fit => [50, 50]
  # end

  version :big do
    process :resize_to_fit => [800, nil]
  end

  version :medium do
    process :resize_to_fit => [480, nil]
  end

  version :small_width do
    process :resize_to_fit => [160, nil]
  end

  version :small_height do
    process :resize_to_fit => [nil, 160]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list
    %w(jpg jpeg png gif)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  before :store, :remember_cache_id
  after :store, :delete_tmp_dir

  # store! nil's the cache_id after it finishes so we need to remember it for deletition
  def remember_cache_id(new_file)
    @cache_id_was = cache_id
  end

  def delete_tmp_dir(new_file)
    # make sure we don't delete other things accidentally by checking the name pattern
    if @cache_id_was.present? && @cache_id_was =~ /\A[\d]{8}\-[\d]{4}\-[\d]+\-[\d]{4}\z/
      FileUtils.rm_rf(File.join(cache_dir, @cache_id_was))
    end
  end

  def filename
    if original_filename
      @name ||= Digest::MD5.hexdigest(File.dirname(current_path)).slice(0, 12)
      "#{@name}.#{file.extension}"
    end
  end

end

2.cocoon配置

application.js添加 //= require cocoon

新建layout_helper.rb

module LayoutHelper

module LayoutHelper
  def stylesheet(*args)
    content_for(:head) { stylesheet_link_tag(*args) }
  end 

  def javascript(*args)
    content_for(:head) { javascript_include_tag(*args) }
  end
end

config/initializers/asset.rb添加如下配置

Rails.application.config.assets.precompile += %w( cocoon.js )

在需要使用cocoon的页面添加

- javascript "cocoon.js"
配置model,一个buyer对应多个附件enclosureclass Buyer < ActiveRecord::Base
  has_many :enclosures, :dependent => :destroy

  accepts_nested_attributes_for :enclosures, reject_if: :all_blank, allow_destroy: true

end

class Enclosure < ActiveRecord::Base
  belongs_to :buyer

  mount_uploader :file, EnclosureUploader
end
配置buyer controller
   def buyer_params
      params.require(:buyer).permit(:alias, :name, :duty_paragraph, :account, :phone, enclosures_attributes: enclosure_params)
    end

    def enclosure_params
      [:id, :file, :_destroy]
    end

新建_enclosure_fields.html.haml

.nested-fields
  .field
    = f.file_field :file, :accept => "image/png, image/jpeg, image/gif", :class => "select-file"
  = link_to_remove_association "删除", f, :class => "btn"

form表单页

.container-fluid
  .row.justify-content-sm-center
    .col-sm-6
      = form_for @buyer do |f|
        - if @buyer.errors.any?
          #error_explanation
            %h2= "#{pluralize(@buyer.errors.count, "error")} prohibited this buyer from being saved:"
            %ul
              - @buyer.errors.full_messages.each do |msg|
                %li= msg
        .form-group.row
          = f.label "截图附件", :class => "col-sm-3 control-label"
          .col-sm-9
            = f.fields_for :enclosures do |enclosure|
              = render 'enclosure_fields', f: enclosure
            .links
              = link_to_add_association "添加文件", f, :enclosures, :class => "btn"
        .form-group.row
          .col-sm-3.offset-sm-2
            = f.submit '保存', :class => "btn btn-success"
          .col-sm-3.offset-sm-1
            = link_to '返回', buyers_path, :class => "btn btn-danger"

图片查看

- @buyer.enclosures.each do |e|
   = image_tag e.file_url(:small_width)

cocoon + carrierwave 多图片上传用法的更多相关文章

  1. CKEditor5 + vue2.0 自定义图片上传、highlight、字体等用法

    因业务需求,要在 vue2.0 的项目里使用富文本编辑器,经过调研多个编辑器,CKEditor5 支持 vue,遂采用.因 CKEditor5 文档比较少,此处记录下引用和一些基本用法. CKEdit ...

  2. [Ting's笔记Day8]活用套件carrierwave gem:(3)Deploy图片上传功能到Heroku网站

    前情提要: 身为Ruby新手村民,创造稳定且持续的学习步调很重要,我用的方法就是一周在IT邦写三篇笔记,希望藉由把笔记和遇到的bug记录下来的过程,能帮助到未来想用Ruby on Rails架站的新手 ...

  3. [Ting's笔记Day6]活用套件carrierwave gem:(1)在Rails实现图片上传功能

    carrierwave是一款经典的图片上传套件,本篇的目标是先在本地端(development)的rails项目试成功gem. (预计中集的进度会练习怎么利用Amazone S3架设图片上传Host, ...

  4. MVC图片上传详解 IIS (安装SSL证书后) 实现 HTTP 自动跳转到 HTTPS C#中Enum用法小结 表达式目录树 “村长”教你测试用例 引用provinces.js的三级联动

    MVC图片上传详解   MVC图片上传--控制器方法 新建一个控制器命名为File,定义一个Img方法 [HttpPost]public ActionResult Img(HttpPostedFile ...

  5. KindeEditor图片上传插件用法

    因业务需要找了款插件 KindeEditor编辑器确认挺好用,但无奈技术有限,上传配置不知,故问度娘! 图片上传对于部分新手来说有时候是一件非常头疼的事,今天来分享一下项目中使用到的这个插件Kinde ...

  6. JS图片上传预览插件制作(兼容到IE6)

    其实,图片预览功能非常地常见.很意外,之前遇到上传图片的时候都不需要预览,也一直没有去实现过.现在手上的项目又需要有图片预览功能,所以就动手做了一个小插件.在此分享一下思路. 一.实现图片预览的一些方 ...

  7. rails使用bootstrap3-wysiwyg可视化编辑器并实现自定义图片上传插入功能

    之前在rails开发中使用了ckeditor作为可视化编辑器,不过感觉ckeditor过于庞大,有很多不需要的功能,而且图片上传功能不好控制不同用户可以互相删除图片,感觉很不好.于是考虑更改可视化编辑 ...

  8. 【HTML5+MVC4】xhEditor网页编辑器图片上传

    准备工作: 创建一个MVC项目中,添加好xhEditor插件 相关用法:http://www.cnblogs.com/xcsn/p/4701497.html 注意事项:xhEditor分为v1.1.1 ...

  9. [上传下载] C# ImageUpload图片上传类教程与源码下载 (转载)

    点击下载 ImageUpload.zip 功能如下图片1.设置属性后上传图片,用法如下 /// <summary> /// 图片上传类 /// </summary> //--- ...

随机推荐

  1. C++之异常处理

     C++ Code  12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 ...

  2. React-Native 样式指南

    https://github.com/doyoe/react-native-stylesheet-guide

  3. AWS系列-S3实现文件服务页面展示

    最近由于业务需求,对于备份的数据存放到S3上面,并需要页面展示.而且还能下载. 把这个桶里面的对象,都在某个静态页面展示.并且 我可以把这个对象下载下来. 首页内容就是 桶里面的对象. 并且可以随时查 ...

  4. 编程之美 set 8 区间重合判断

    Leetcode 上有连续的两道题, 一个是 insert interval, 一个是 merge interval, 其中 insert interval 是 merge interval. 其中 ...

  5. THINKPHP5加载公共头部尾部模板方法

    之前在3.2中用 <include file="public/header" /> 后来发现在thinkphp5中应该这样写才行 {include file=" ...

  6. log4j2设置日志文件读写权限(filePermissions)

    spring-boot使用log4j2作为日志插件的时候需要设置日志文件的读写权限,可以File 上增加filePermissions,如: <File name="File" ...

  7. 常用的一些javascript小技巧

    (转载)常用的一些javascript小技巧: http://bbs.blueidea.com/thread-2201069-1-1.html

  8. 浏览器中使用 ES6 import

    html 中的 head 标签引入: <script src="test.js" type="module"></script> tes ...

  9. js 空正则匹配任意一个位置

    看一个正则 这里明显,起到匹配作用的是 | 后的,可 | 后什么都没有,原理不知道,也没有搜到文献,只有在 Reg101 上是这样解释的, 所以得出结论: js 中,空正则匹配任意一个位置. 不过,这 ...

  10. Jsp 公用标签库

    <%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib prefix=" ...