Skip to content

How to: Add, remove and reorder images using multiple file upload

Mitsuhiro Shibuya edited this page Jun 19, 2019 · 1 revision

Improved multiple file upload feature in CarrierWave 2.0.0 enables intuitive way of editing files.

Let's assume we have mount_uploaders :images, ImageUploader in Album model.

Gemfile

gem 'jquery-ui-rails'

application.js

//= require rails-ujs
//= require jquery
//= require jquery-ui/widgets/sortable
//= require_tree .

$(function () {
  $('.image-sortable').sortable({
    axis: 'y',
    items: '.image'
  });

  $('.add-image').click(function () {
    $('.image-sortable').append('<div class="image"><input multiple="multiple" type="file" name="album[images][]"></div>');
  });

  $('.remove-image').click(function () {
    $(this).parent('.image').remove();
  });
});

_form.html.erb

<%= form_with(model: album, local: true, html: { multipart: true }) do |form| %>
  <% if album.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(album.errors.count, "error") %> prohibited this album from being saved:</h2>

      <ul>
      <% album.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title, id: :album_title %>
  </div>

  <div class="field">
    <%= form.label :images %>
    <div class="image-sortable">
      <% album.images.each do |image| %>
        <div class="image">
          <%= hidden_field :album, :images, multiple: true, value:  image.cache_name || image.identifier %>
          <%= image_tag(image.url, height: 50) %>
          <button type="button" class="remove-image">Remove</button>
        </div>
      <% end %>
      <div class="image">
        <%= form.file_field :images, multiple: true %>
      </div>
    </div>
    <button type="button" class="add-image">Add more images</button>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
Clone this wiki locally