Image preview function implementation

Introduction

I am making an original app with Rails. We have implemented an image posting function in this app. Since the preview was displayed after uploading the image (before saving it in the database), write it down.

table of contents

  1. Preparation
  2. Implementation of preview function

1. Preparation

Since JavaScript is used, prepare a js file. Define it to work when the page loads.

app/javascript/packs/preview.js


document.addEventListener('DOMContentLoaded', function(){
  const ImageList = document.getElementById('image-list');
});

The image-list obtained by getElementById is the id name of the div tag on html. Show a preview on this div tag. Therefore, I will add it to html (this time I placed it under the submit button).

Ruby:○○.html.erb


<%= f.file_field :image %>
<%= f.submit 'Send' %>
<div id="image-list"></div>

Also, edit application.js so that the created js file is loaded. Commented out turbolinks are gems that speed up screen transitions. It seems that it does not read all the information on the page, but only HTML. Therefore, the event set in JavaScript may not fire.

app/javascript/packs/application.js


// require("turbolinks").start()  //Comment out
require("@rails/activestorage").start()
require("channels")
require('./preview')  //Append

2. Implementation of preview function

3 steps in total. ** 2-1. Acquisition of image information First, get the image information and generate the URL. Image information is acquired when the value of the input element is changed.

app/javascript/packs/preview.js


document.addEventListener('DOMContentLoaded', function(){
  const ImageList = document.getElementById('image-list');
 
  document.getElementById('desk_image').addEventListener('change', function(e){
  //↑desk_image is the id of the image selection button//
    const file = e.target.files[0];
    const blob = window.URL.createObjectURL(file);
  });
});

The selected image is stored in an array called files in the fired event e, target. Define it in the file variable and generate the URL with window.URL.createObjectURL.

** 2-2. Display of acquired image ** Create a div element and an img element to insert the acquired image with createElement. Then display the generated element in the browser.

app/javascript/packs/preview.js


document.addEventListener('DOMContentLoaded', function(){
  const ImageList = document.getElementById('image-list');
 
  document.getElementById('desk_image').addEventListener('change', function(e){
    const file = e.target.files[0];
    const blob = window.URL.createObjectURL(file);

  //Generate a div element to display an image
    const imageElement = document.createElement('div');

  //Generate image elements to display and insert images
    const blobImage = document.createElement('img');
    blobImage.setAttribute('src', blob);

  //Display the generated HTML element in the browser
    imageElement.appendChild(blobImage);
    ImageList.appendChild(imageElement);
  });
});

Add an element inside the parent element specified by appendChild (Usage: parent element.appendChild (child element)).

** 2-3. Error avoidance and editability ** The image will be displayed by 2-2. However, an error is displayed on the console other than the image posting page. To avoid this, add a condition. Describe to apply when there are new and edit in the URL (when posting a new image or editing).

app/javascript/packs/preview.js


if (document.URL.match( /new/ ) || document.URL.match( /edit/ )) {
  document.addEventListener('DOMContentLoaded', function(){
    const ImageList = document.getElementById('image-list');
 
―――――――――――――――― Omitted ――――――――――――――――――――――
    //Display the generated HTML element in the browser
      imageElement.appendChild(blobImage);
      ImageList.appendChild(imageElement);
    });
  });
}

When editing an image, delete the existing preview and then display the preview of the new image.

app/javascript/packs/preview.js


if (document.URL.match( /new/ ) || document.URL.match( /edit/ )) {
  document.addEventListener('DOMContentLoaded', function(){
    const ImageList = document.getElementById('image-list');

    document.getElementById('message_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);
      const imageElement = document.createElement('div');
      const blobImage = document.createElement('img');
      blobImage.setAttribute('src', blob);
      imageElement.appendChild(blobImage);
      ImageList.appendChild(imageElement);
    });
  });
}

that's all

Recommended Posts

Image preview function implementation
Implementation of image preview function
Image preview function
[Rails] Implementation of image preview function
Image posting function
[Rails] Implementation of image enlargement function using lightbox2
Follow function (Ajax) implementation
Implementation of search function
Rails search function implementation
Implementation of pagination function
Search function [copype implementation]
[Implementation procedure] Implement image upload function with Active Storage
[Ruby on Rails] Post image preview function in refile
Rails fuzzy search function implementation
[Rails 6] Implementation of search function
[Rails] Implementation of category function
Implementation of category pull-down function
Login function implementation with rails
[Rails] Implementation of tutorial function
[Rails] Implement image posting function
[Rails] Implementation of like function
[Rails 6] Pagination function implementation (kaminari)
[Rails] Implementation of CSV import function
[Rails] Asynchronous implementation of like function
Let's roughly implement the image preview function with Rails + refile + jQuery.
[Rails] About implementation of like function
[Rails] Implementation of user withdrawal function
[Rails] Implementation of CSV export function
I tried to implement the image preview function with Rails / jQuery
[Rails] gem ancestry category function implementation
[Ruby on Rails] Comment function implementation
Yes, let's preview the image. ~ part5 ~
Show preview when editing user image
[Rails 6] Like function (synchronous → asynchronous) implementation
[Rails] Comment function implementation procedure memo
Error encountered in tagging function implementation
Implementation of like function in Java
Implementation of user authentication function using devise (2)
[Ruby on Rails] Follow function implementation: Bidirectional
Implementation of user authentication function using devise (1)
Rails [For beginners] Implementation of comment function
Where the follow function implementation is stuck
Rails Basic CRUD function implementation procedure scaffold
[Rails 6] Implementation of SNS (Twitter) sharing function
Implementation of user authentication function using devise (3)
[Vue.js] Implementation of menu function Implementation version rails6
[Ruby on rails] Implementation of like function
[Vue.js] Implementation of menu function Vue.js introduction rails6
Login function implementation by Spring Security (securityConfig)
Multiple image upload function using Rails Carrierwave