Rails+javascript - image preview before upload

后端 未结 4 1177
太阳男子
太阳男子 2021-02-13 16:08

I want to show an image preview before upload, for that I am using the code given below.

It works with firefox, but doesn\'t work with IE8

<%= image_t         


        
相关标签:
4条回答
  • 2021-02-13 16:29

    I do use https://github.com/blueimp/jQuery-File-Upload for file uploads.

    In the spec of this jQuery plugin, you can read:

    Preview images can be loaded and displayed for local image files on browsers supporting the URL or FileReader interfaces.

    IE8 is not HTML5 compliant thus not compatible with FileReader. You should use flash or friends to achieve that.

    Firefox is HTML5 compliant...

    0 讨论(0)
  • 2021-02-13 16:36

    In ERB: Take input, and give it a class name and dynamic id, and also make a image tag with dyanamic id where you will show the preview pic.

    <%= f.file_field :photo, :class => 'photo_upload', :id => "image_#{image.id}" %>  
    <%= image_tag("preview.png", :id => "image_#{image.id}_medium") %>
    

    In JAVASCRIPT:

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();            
          reader.onload = function (e) {
              $(document.getElementById(input.id + "_medium")).attr('src', e.target.result);
            }
    
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    $(".photo_upload").change(function(){
        readURL(this);
    });
    
    0 讨论(0)
  • 2021-02-13 16:45

    This solution works like a charm and has a conditional load for Internet Explorer so it should work for you.

    I put the code here just in case the source dies:

    Script:

    <!-- Assume jQuery is loaded -->
    <script>
      function readURL(input) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();
    
          reader.onload = function (e) {
            $('#img_prev')
              .attr('src', e.target.result)
              .width(150)
              .height(200);
          };
    
          reader.readAsDataURL(input.files[0]);
        }
      }
    </script>
    

    In the HTML:

    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    </head>
    <body>
      <input type='file' onchange="readURL(this);" />
      <img id="img_prev" src="#" alt="your image" />
    </body>
    
    0 讨论(0)
  • 2021-02-13 16:45

    I had made a pure JS solution with fallback for IE users: http://mootools.standupweb.net/dragndrop.php

    0 讨论(0)
提交回复
热议问题