Image preview opens for duplicated div

前端 未结 3 1023
小蘑菇
小蘑菇 2021-01-26 00:24

I have a function that uploads and image and adds a preview to this image, and i have two buttons, when i click on the first one it clicks on the input type file and opens it, a

3条回答
  •  生来不讨喜
    2021-01-26 00:30

    One common problem I see with this file previews are that most of them are unable to correctly render jpg's rotated with exif orientation

    The second thing is that it's better to use URL.createObjectURL rather then using a base64 dataURL. That also raises an other issue and that is that most developers forget to revoked objectURL's

    That is why i have created Screw-FileReader so you can easily call blob.image() and get a image back with a object url that is automatically revoked and also has a exif auto-rotation built in using canvas.

    var $file = $('#filepicker').on('change', preview);
    
    $('.uploader button').click(function() {
      $file.click()
    })
    
    function preview(evt) {
      var preview = document.querySelector('.preview')
      
      Array.from(this.files).forEach(function(file) {
        file.image().then(function(img) {
          preview.appendChild(img)
        }, function() {
          // err not an image...
        })
      })
    }
    input {
      display: none;
    }
    
    
    
    

    the third thing i notis with Soltani Neji answer was that when you click dublicate button before the first upload button it dose unexpected things. it don't keep track of the index so well.

    Now to my suggestions: Use the multiple attribute instead and just have one button to make it simpler. it also helps to add the accept="image/*" to filter out only images

提交回复
热议问题