首页 > 解决方案 > 如何删除预览图像并从输入类型文件中删除多个?

问题描述

嗨,大家好。删除预览图像的问题已解决,但我还需要从输入中删除相同的图像。我尝试了很多方法,但没有成功。下面是我的 html 和我正在使用的脚本。如果这是做我想做的事情的最佳方式,我不知道。我搜索了很多,但我很多人都有同样的问题,但没有答案。我只找到了一种从输入中删除所有图像的方法,而不是我从预览中删除的图像。希望大家能救救我!。

function handleFileSelect(event) {
  var input = this;
  if (input.files && input.files.length) {
    var filesAmount = input.files.length;
    for (i = 0; i < filesAmount; i++) {
      var reader = new FileReader();
      this.enabled = false
      reader.onload = (function(e) {
        var span = document.createElement('span');
        span.innerHTML = ['<img id="test" class="thumb" src="', e.target.result, '" title="', escape(e.name), '"/><span class="remove_img_preview"></span>'].join('');
        document.getElementById('preview').insertBefore(span, null);
      });
      reader.readAsDataURL(input.files[i]);
    }
  }
}

$('#photos').change(handleFileSelect);

$('#preview').on('click', '.remove_img_preview', function() {
  $(this).parent('span').remove();
  $(this).val("");
});
.thumb {
  width: 80px;
  height: 50px;
  margin: 0.2em -0.7em 0 0;
}

.remove_img_preview {
  position: relative;
  top: -12px;
  right: 7px;
  background: black;
  color: white;
  border-radius: 50px;
  font-size: 0.9em;
  padding: 0 0.3em 0;
  text-align: center;
  cursor: pointer;
}

.remove_img_preview:before {
  content: "×";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="{{route('employee.store.settlement')}}" enctype="multipart/form-data" method="POST">


  <div class="form-group">
    <label for="photos">Selecione fotos do povoado</label>
    <input type="file" name="photos[]" id="photos" multiple="multiple" accept="image/*">
  </div>
  <div class="form-group" style="float: right">
    <button type="submit" class="btn btn-success">Cadastrar</button>
  </div>
  <div>
    <style>

    </style>
    <div id="preview"></div>
  </div>
</form>

标签: javascripthtmljquery

解决方案


恐怕是坏消息。由于安全限制,FileList API 是只读的。您可以通过此方法将其全部清除:https ://stackoverflow.com/a/13351234/1772933

另一个参考:https ://stackoverflow.com/a/3162319/1772933


推荐阅读