If you are using bootstrap_form
, the following steps are required.
If you are using bootstrap_form
, this gem will create a nice UI, but in this implementation it gets in the way.
<%= f.file_field :image %>
So make sure that the bootstrap style isn't applied.
<%= f.file_field_without_bootstrap :image %>
<%= f.label :image do %>
<%= image_tag('user.png') %>
<%= f.file_field_without_bootstrap :image, style: 'display:none' %>
<% end %>
Simply enclose the image and file_field
in label
and hide file_field
with CSS.
If you replace the image part with an icon, you can upload by clicking the icon.
Add an appropriate class name to the image and uploader so that you can get the element from JS.
<%= f.label :image do %>
<%= image_tag('user.png', class: 'avatar') %>
<%= f.file_field_without_bootstrap :image, class: 'uploader', style: 'display:none' %>
<% end %>
Encodes the image selected in JavaScript to base64 and replaces it with the original image.
window.addEventListener('load', () => {
const uploader = document.querySelector('.uploader');
uploader.addEventListener('change', (e) => {
const file = uploader.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const image = reader.result;
document.querySelector('.avatar').setAttribute('src', image);
}
});
});
Recommended Posts