Select an image from a file and allow it to display your selected image before submitting.
The image is as follows.
-It is possible to set jQuery. -Use Rails version 5.2 ・ Use Haml
edit.html.haml
.editmain_right
.editmain_right_form
.editmain_right_form_sub
%span.icon
%span.icontext Upload profile image
.editmain_right_form_main
.editmain_right_form_main_ajax
.editmain_right_form_main_file
= f.file_field :image, class: "image_form"
%span.texpic
Photo upload
edit.js
$(document).on('turbolinks:load', function() {
$(function(){
//Add event for image file preview display Register an event that fires when file is selected
$('form').on('change', 'input[type="file"]', function(e) {
var file = e.target.files[0],
reader = new FileReader(),
$subsubimageboxs = $(".editmain_right_form_sub");
t = this;
//Do nothing except for image files
if(file.type.indexOf("image") < 0){
return false;
}
//Event registration when file reading is completed
reader.onload = (function(file) {
return function(e) {
//Delete existing preview
$subsubimageboxs.empty();
// .Added an image tag to display the loaded image in the preview area
$subsubimageboxs.append($('<img>').attr({
src: e.target.result,
width: "150px",
class: "editmain_right_form_sub",
title: file.name
}));
};
})(file);
reader.readAsDataURL(file);
});
});
});