Rails4 after upload completion by input and then how to trigger bootstrap modal?

烂漫一生 提交于 2019-12-11 17:07:16

问题


My Gemfile:

gem 'rails', '4.2.8'
gem 'carrierwave', '~> 1.2', '>= 1.2.2'
gem 'mini_magick', '~> 4.8'
gem 'Jcrop', '~> 0.1.0'

Now I want to use form_for upload the user picture, my show.html.erb:

    <%= form_for @user, :html => {:multipart => true} do |f| %>
  <div class="row " id="user_avatar_crop">
    <!-- Choose Image -->
    <div class="col-md-12">
      <%= f.file_field :picture, id: :user_avatar, onchange: 'this.form.submit()'%>
    </div>
  </div>
<% end %>

<!-- Modal -->
<div id="uploadModalContent">

</div>

<!-- Show user picture -->
<% if @user.picture? %>
  <%= image_tag @user.picture.url(:thumb), :alt => @user.name+"_avatar" %>
  <% else %>
  <%= image_tag @user.picture.url(:thumb),:alt => @user.name+"_default" %>
  <% end %>

My user_controller.rb :

def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      if params[:user][:picture].present?
        respond_to do |format|
          format.html do
            flash[:warning] = "Template missing"
            redirect_to @user
          end
          format.js { render template: 'users/update.js.erb'}
        end
      else
        redirect_to @user
        flash[:success] = "Success update"
      end
    else
      render :edit
    end
  end

My update.js.erb:

$('#uploadModalContent').html("<%= j render "users/modal"%>");
$('#upload-modal').modal('show');

My _modal.html.erb:

<div class="modal fade" id="upload-modal" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Crop Image</h4>
      </div>
      <div class="modal-body">
        <div class="col-md-8">
          <%= image_tag @user.picture_url(:large), id: "cropImage" %>
        </div>
        <div class="col-md-4">
          <h4>Preview</h4>
          <div style="width:100px; height:100px; overflow:hidden;">
            <%= image_tag @user.picture.url(:large), :id => "user_preview" %>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <%= form_for @user do |f| %>
          <% %w[x y w h].each do |attribute| %>
            <%= f.hidden_field "crop_#{attribute}" %>
          <% end %>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <%= f.submit "crop" %>
        <% end %>
      </div>
    </div>
  </div>
</div>

Now I need after upload picture, the _modal.html.erb can display. But it seems that format.js { render template: 'users/update.js.erb'} in user_controller.rb cann't work. This is for why?

And what should I do in user_controller.rb that after input complete onchange: 'this.form.submit()' it can render to the modal window? Thanks so much for your help.


回答1:


I found another way to upload images in rails. I arrived at the conclusio that is the best method I know so far. You have to use carrierwave gem. I will put now the code needed in order to use it. Anyway if you can check the github repo or this post.

Ok so lets go. You will have first to install the gem globally, but even locally in your project.

$ gem install carrierwave

In Rails, add it to your Gemfile:

gem 'carrierwave', '~> 1.0'

Now restart the server to apply the changes.

Start off by generating an uploader:

rails generate uploader Photos

this should give you a file in:

# app/uploaders/photos_uploader.rb
class PhotosUploader < CarrierWave::Uploader::Base
  storage :file
  # will save photos in /app/public/uploads
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

Create Photos migration

class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.string :name, :null => false
      t.binary :data, :null => false
      t.string :filename
      t.string :mime_type

      t.timestamps null: false
    end
  end
end

And model

require 'carrierwave/orm/activerecord'
class Photo < ActiveRecord::Base
  mount_uploader :data, PhotosUploader
end

Then controller

class PhotosController < ApplicationController
  def index
    @photos = Photo.all
  end
  def show
    @photo = Photo.find(params[:id])
  end
  def new
    @photo = Photo.new
  end
  def create
    # build a photo and pass it into a block to set other attributes
    @photo = Photo.new(photo_params)
    # normal save
    if @photo.save
      redirect_to(@photo, :notice => 'Photo was successfully created.')
    else
      render :action => "new"
    end
  end
  private
    def photo_params
      params.require(:photo).permit!
    end
end

The form upload:

<!-- new.html.erb -->
<%= form_for(@photo, :html => {:multipart => true}) do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :data %>
    <%= f.file_field :data %>
  </div>
  <div class="actions">
    <%= f.submit "Upload" %>
  </div>
<% end %>

And you load the file in a view like this.

<!-- show.html.erb -->
<h3>Photo: <b><%= @photo.name %></b></h3>
<%= image_tag @photo.data.url %>

you could also trigger a modal after image upload like this:

# app/assets/javascripts/photos.coffee
$ ->
  alert('Photo Uploaded - You can launch modal here')

All right that's all. Let me know how is going!



来源:https://stackoverflow.com/questions/50411985/rails4-after-upload-completion-by-input-and-then-how-to-trigger-bootstrap-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!