I would like to preview by replacing the existing image with the existing one before uploading the image with rails.

Asked 1 years ago, Updated 1 years ago, 77 views

When previewing an image, a new preview image appears next to the existing image.
What should I do to display it so that it can be replaced with an existing image?
Thank you for your cooperation.

<div class="field">
  <%[email protected] [email protected]?%>
  <%=f.label:picture, 'image'%>
  <%=f.hidden_field:picture_cache%>
  <img id="img_prev" width=200 height=200 src="#" class="img-thumbnail hidden"/>
  <%=f.file_field:picture, :id=>'post_post_img'%>

  <script type="text/javascript">
    $(function(){
      function readURL(input){
        if(input.files&input.files[0]){
          var reader = new FileReader();
          reader.onload=function(e){
            $('#img_prev') .attr('src', e.target.result);
          }
          reader.readAsDataURL(input.files[0]);
        }
      }
      $("#post_post_img").change(function(){
        $('#img_prev').removeClass('hidden');
        readURL(this);
      });
    });
  </script>
</div>

javascript ruby-on-rails

2022-09-30 21:19

1 Answers

How about giving an id to an image_tag that displays an existing image and changing the src of the DOM when selecting a file?(Examples below)

<div class="field">
  <%[email protected], id: "img_prev" [email protected]?%>
  <%=f.label:picture, 'image'%>
  <%=f.hidden_field:picture_cache%>
  <%=f.file_field:picture, :id=>'post_post_img'%>

  <script type="text/javascript">
    $(function(){
      function readURL(input){
        if(input.files&input.files[0]){
          var reader = new FileReader();
          reader.onload=function(e){
            $('#img_prev') .attr('src', e.target.result);
          }
          reader.readAsDataURL(input.files[0]);
        }
      }
      $("#post_post_img").change(function(){
        readURL(this);
      });
    });
  </script>
</div>


2022-09-30 21:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.