Open emma1278-my opened 3 months ago
<%= javascript_pack_tag 'profiles' %> <div class="form-group"> <%= f.label :image, class: "label" %> <%= f.file_field :image, accept: 'image/jpeg, image/gif, image/png', id: "image-select-btn" %> </div> <div class="post-image-prev"> <% if @post.image? %> <%= image_tag @post.image.thumb.url, alt: "post-image", id: "img_prev", size: "150" %> <% else %> <%= image_tag "post-default.png", alt: "post-image", id: :img_prev, size: "150" %> <% end %> </div>
- [x] app/javascript/packs/profiles.jsファイルを作成
$(function () { function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#img_prev").attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#image-select-btn").change(function () { readURL(this); }); });
https://qiita.com/takuma_0625/items/999a639e8250120b0ac6
$(function () { function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#img_prev").attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#image-select-btn").change(function () { readURL(this); }); });