environment Rails 5.2.4.4
** Premise ** image_id column in user table
procedure ① Give id to image_tag Give id for processing in JavaScript. Here, ʻid: "img_prev" `is used.
<%= attachment_image_tag @user, :image, size: "300x300", fallback: "no_profile.jpg ", size: "300x300" , id: "img_prev"%>
② Write JavaScript at the bottom of the page When the value of the image file field changes Read the URL of the image file with image_tag and display the image.
<script>
$(function(){
$('#user_image').on('change', function (e) { #Get information from id
var reader = new FileReader(); #Get existing image url
reader.onload = function (e) {
$(".image").attr('src', e.target.result);
} #This is for image acquisition
reader.readAsDataURL(e.target.files[0]); #Insert the url of the uploaded image into the obtained url
});
});
</script>
The image preview function has been implemented.
Recommended Posts