[JQuery] Form selection preview display from file

Introduction

Select an image from a file and allow it to display your selected image before submitting.

The image is as follows. 画面収録 2020-05-31 13.21.05.mov.gif

As a premise

-It is possible to set jQuery. -Use Rails version 5.2 ・ Use Haml

Let's set the view file

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

Set jQuery

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);
  });
});
});

Recommended Posts

[JQuery] Form selection preview display from file
From (form)