2018年10月1日|
|
コメントなし
bootswatchでファイル選択のスタイルをリッチにする
概要
bootswatchとrails-assets-bootstrap-fileinputをつかって、ファイル選択の見た目をリッチにしたかったのですが、
gem 'bootstrap-sass' gem 'bootswatch-rails'
↑このようなGemfile設定だとrails-assets-bootstrapと競合してしまい、
Incompatible units: 'rem' and 'px'.
↑とエラーがでてしまったので、以下のgemを使って解決しました。
Gemfile
source 'https://rails-assets.org' do gem 'rails-assets-bootstrap-sass-official' gem 'rails-assets-bootswatch-sass' gem 'rails-assets-bootstrap-fileinput' end
app/views/share/_image_control.html.erb
<div class="row">
<div class="field">
<%= f.label :image, class: "control-label" %>
<div id="image_control_area">
<% if model.image? %>
<div class="thumbnail">
<%= image_tag model.image.url, id: 'image_preview' %>
</div>
<% end %>
</div>
<!-- 既存レコード(DBに保存されている)かつ、画像が存在する場合 -->
<% if model.persisted? && model.image? %>
<div class="form-group">
<div class="checkbox pull-right">
<%= f.check_box :remove_image, class: 'checkbox' %>
<%= f.label :remove_image, class: "control-label", style: "padding:0px" %>
</div>
</div>
<% end %>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="field">
<%= f.file_field :image %>
<%= f.hidden_field :image_cache %>
</div>
</div>
</div>
<script>
$("#<%= model.model_name.singular %>_image").fileinput({
allowedFileExtensions: ["jpg", "png", "gif"],
showUpload: false,
showPreview: false,
maxImageWidth: 3000,
maxImageHeight: 3000,
browseLabel: "ファイル選択",
removeLabel: "削除",
msgPlaceholder: "ファイル選択..."
}).on('fileloaded', function(event, f, previewId, index, reader) {
console.log("fileloaded");
console.log(f);
if( f != null && f.type.match('image.*')){
var reader = new FileReader();
// Readerのロード完了時のハンドラ
reader.onload = (function(){
// reader.resultにはファイルがdataURL化された文字列が入る
$('#image_control_area').html('<div class="thumbnail"><img src="' + reader.result + '"></div>');
});
// dataURL形式で読み込み
reader.readAsDataURL(f);
// フィルタをはずす
changeImageAreaCss( 0 );
}else{
$('#image_control_area').html('');
}
}).on('filecleared', function(event) {
console.log("filecleared");
$('#image_control_area').html('');
});
function changeImageAreaCss( fade_time )
{
if ($('#<%= model.model_name.singular %>_remove_image').is(':checked')) {
$('#image_control_area').animate({'opacity': 0.2}, fade_time);
return true;
} else {
$('#image_control_area').animate({'opacity': 1}, fade_time);
return false;
}
}
window.onload = function(){
changeImageAreaCss( 0 );
}
$('#<%= model.model_name.singular %>_remove_image').change(function(){
changeImageAreaCss( 100 );
});
</script>
app/views/yourview/yourview.html.erb
<%= form_for(@your_model) do |f| %>
<%= render partial: "share/image_control", locals: { f: f, model: @your_model } %>
<% end %>
モデルにはCarrywaveを使用しています。
class YourModel < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
結果
ファイル選択前

ファイル選択後
