When posting an image, I felt that it was difficult to understand because only the name of the image file was displayed, so I implemented a preview function.
** Before implementing preview function **
** 1. Create a js file to implement the preview function. Create preview.js in app/javascript/packs ** → app / javascript / packs / preview.js
** 2. Edit application.js so that preview.js can be loaded. ** **
app/javascript/packs/application.js
require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")
require('./preview') #Append
** 3. Specify where the image will be displayed in the view file. ** **
html:views/ideas/new.html.erb
<div class="img-upload">
<div class="left-img-upload">
<div class="weight-bold-text">
Related images(Please attach any related images)
</div>
<div class="click-upload">
<p>Click to upload file</p>
<%= f.file_field :image, id:"idea-image" %>
</div>
</div>
<div class="right-img-upload">
<div id="image"></div> <!--Append-->
</div>
</div>
** Write the preview function code in preview.js created in 1. ** **
app/javascript/packs/preview.js
if (document.URL.match( /new/ ) || document.URL.match( /edit/ )) {
document.addEventListener('DOMContentLoaded', function(){
const ImageList = document.getElementById('image');
const createImageHTML = (blob) => {
//Generate a div element to display an image
const imageElement = document.createElement('div');
//Generate an image to display
const blobImage = document.createElement('img');
blobImage.className="preview"; //← Class name is given to img generated by createElement
blobImage.setAttribute('src', blob);
//Display the generated HTML element in the browser
imageElement.appendChild(blobImage);
ImageList.appendChild(imageElement);
};
document.getElementById('idea-image').addEventListener('change', function(e){
//Delete an existing image only if the image is displayed
const imageContent = document.querySelector('img');
if (imageContent){
imageContent.remove();
}
const file = e.target.files[0];
const blob = window.URL.createObjectURL(file);
createImageHTML(blob);
});
});
}
python
.preview {
height: 250px;
width: 250px;
object-fit: contain;
}
Thanks to the images being displayed, it is easier to understand the image you have selected.
It was a good review because I didn't implement it using javascript very much. Also, I learned how to give a class name to the element created by createElement, which was a great learning experience.
Recommended Posts