多个(单个)文件字段上的FileReader缩略图预览

时间:2018-02-13 13:02:02

标签: javascript filereader reset preview

将javascript应用于多个(单个)文件上传字段的最佳方法是,这目前在单个字段上工作得很好,但是目标是ID,我假设有一个更优雅的方式来编写javascript而不是重复每个ID ?:

function PreviewImage() {
  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

  oFReader.onload = function(oFREvent) {
    document.getElementById("uploadPreview").src = oFREvent.target.result;
    document.getElementById('uploadPreview-container').style.display = 'block';
  };
};

function ResetImage() {
  document.getElementById('uploadPreview-container').style.display = 'none';
  document.getElementById('uploadImage').value = '';
};
#uploadPreview {
  width: 100px;
}

#uploadPreview-container {
  display: none;
  position: relative;
  width: 100px;
}

#uploadReset {
  position: absolute;
  top: 0;
  right: 0;
}
<div id="uploadPreview-container">
  <img id="uploadPreview" />
  <div id="uploadReset"><a href="javascript:void(0)" onclick="ResetImage()" title="Reset Image Upload">RESET</a></div>
</div>
<div><input id="uploadImage" type="file" name="myPhoto" data-max-size="248" onChange="PreviewImage();" /></div>

1 个答案:

答案 0 :(得分:0)

你是对的,你必须使用一个类名而不是一个id,因为你不知道将添加多少个图像你必须动态创建img个元素

  1. 添加multiple属性,允许用户在单个文件输入中上传多个图像。
  2. 循环浏览文件并为每个文件添加图像预览。
  3. &#13;
    &#13;
    function PreviewImage() {
      Array.from(document.getElementById("uploadImage").files).forEach(file=>{
        var oFReader = new FileReader();
        oFReader.readAsDataURL(file);
        oFReader.onload = function(oFREvent) {
          var img = new Image();
          img.src = oFREvent.target.result;
          img.className = "uploadPreview";
          document.getElementById("preview_div").appendChild(img);
          document.getElementById('uploadPreview-container').style.display = 'block';
        };
      });
    };
    
    function ResetImage() {
      document.getElementById('uploadPreview-container').style.display = 'none';
      document.getElementById('uploadImage').value = '';
    };
    &#13;
    .uploadPreview {
      width: 100px;
    }
    
    #uploadPreview-container {
      display: none;
      position: relative;
      width: 100px;
    }
    
    #uploadReset {
      position: absolute;
      top: 0;
      right: 0;
    }
    &#13;
    <div id="uploadPreview-container">
      <div id=preview_div></div>
      <div id="uploadReset"><a href="javascript:void(0)" onclick="ResetImage()" title="Reset Image Upload">RESET</a></div>
    </div>
    <div><input id="uploadImage" type="file" name="myPhoto" data-max-size="248" onChange="PreviewImage();" multiple /></div>
    &#13;
    &#13;
    &#13;