【问题标题】:File Api should delete preview when button is clicked单击按钮时,文件 Api 应删除预览
【发布时间】:2022-01-15 17:39:10
【问题描述】:

我正在尝试构建文件上传,并希望在单击灰色的“清除内容”按钮(它是德语)后清除预览。文件输入元素会自行清空,但预览不会自行更新。

这是我的代码:

function handleFileSelect(evt) {
  var files = evt.target.files; // FileList object

  // Loop through the FileList and render image files as thumbnails.
  for (var i = 0, f; f = files[i]; i++) {

    // Only process image files.
    if (!f.type.match('image.*')) {
      continue;
    }

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
      return function(e) {
        // Render thumbnail.
        var span = document.createElement('span');
        span.innerHTML = ['<img class="thumb" src="', e.target.result,
                          '" title="', escape(theFile.name), '" style=" height: 100px; max-width: 150px; border: 1px solid #000; margin: 10px 5px 0 0;"/>'].join('');
        document.getElementById('list').insertBefore(span, null);
      };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

Bootstrap 5 中的我的 HTML 模态

<div class="form-check">
  <div class="input-group">
      <!--<input type="file" class="form-control" id="files" name="uploaded_file[]" accept="image/jpeg,image/gif,image/png,application/pdf" multiple="multiple"/>-->
      <button type="button" class="btn btn-outline-send" data-bs-toggle="modal" data-bs-target="#exampleModal">
      <i class="fas fa-upload fa-2x"></i>
          <!--Dokumente hochladen-->
      </button>
      <!-- Modal -->
      <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Bitte wählen Sie aus, welche Dokumente Sie hochladen möchten.</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
            <input type="file" class="form-control" id="files" name="uploaded_file[]" accept="image/jpeg, image/jpg, image/gif, image/png, application/pdf" multiple="multiple" value=""/>
            <output id="list"></output>
            <small>
                <strong>
                    <br>
                    Hinweis: Es können <u>maximal 19</u> Dateien aufeinmal versendet werden! <br>Unterstützte Dateiformate: PDF, JPG und PNG
                  </strong>
              </small>
            </div>
            <div class="modal-footer">
            <button type="button" class="btn btn-outline-send" data-bs-dismiss="modal">Weiter</button>
            <button type="button" id="clearFiles">Inhalte löschen</button>
              <!--<button type="button" class="btn btn-primary">Save changes</button>-->
            </div>
          </div>
        </div>
      </div>
  </div>
</div>

还有一张它现在的样子 example Image

【问题讨论】:

  • 您的脚本正在创建一些 span 元素以插入到 #list 元素之前。现在,当单击“清除内容”按钮时,应针对那些 span 进行删除。 - 由于您没有发布任何 HTML 和按钮 click 处理程序,因此我无法确切告诉您该怎么做。 -- 编辑你的问题。
  • @LouysPatriceBessette 我已经添加了我的 HTML 代码

标签: javascript jquery jquery.fileapi


【解决方案1】:

我为Inhalte löschen 按钮添加了一个事件监听器:

// To clear the images
document.querySelector("#clearFiles").addEventListener("click", function(){
  document.querySelector("#list").innerHTML = "";
});

请注意,我还将.insertBefore(span, null); 更改为.append(span)。所以现在图像被附加到#list div 中,而不是之前。它使清除#list的全部内容变得更加容易。

function handleFileSelect(evt) {
  var files = evt.target.files; // FileList object

  // Loop through the FileList and render image files as thumbnails.
  for (var i = 0, f; f = files[i]; i++) {

    // Only process image or PDF files.
    if (!f.type.match('image.*') && !f.type.match('pdf')) {
      console.log(f.type)
      continue;
    }
    
    // A flag to know if the file is an image or a PDF
    let source_is_image = true;
    if(!f.type.match('image.*')){
      source_is_image = false;
    }

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
      return function(e) {
        // Render thumbnail.
        var span = document.createElement('span');
        
        // Based on the flag, decide to use the image or the PDF logo
        var file = source_is_image ? e.target.result : "https://upload.wikimedia.org/wikipedia/commons/8/87/PDF_file_icon.svg";
        
        span.innerHTML = ['<img class="thumb" src="', file, '" title="', escape(theFile.name), '"/>'
          ].join('');
        document.getElementById('list').append(span);
      };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

// To clear the images
document.querySelector("#clearFiles").addEventListener("click", function(){
  document.querySelector("#list").innerHTML = "";
});
/* This can be in the CSS instead of inline style */
.thumb{
  height: 100px;
  max-width: 150px;
  border: 1px solid #000;
  margin: 10px 5px 0 0;
}
<div class="form-check">
  <div class="input-group">
    <!--<input type="file" class="form-control" id="files" name="uploaded_file[]" accept="image/jpeg,image/gif,image/png,application/pdf" multiple="multiple"/>-->
    <button type="button" class="btn btn-outline-send" data-bs-toggle="modal" data-bs-target="#exampleModal">
      <i class="fas fa-upload fa-2x"></i>
      <!--Dokumente hochladen-->
    </button>
    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Bitte wählen Sie aus, welche Dokumente Sie hochladen möchten.</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <input type="file" class="form-control" id="files" name="uploaded_file[]" accept="image/jpeg, image/jpg, image/gif, image/png, application/pdf" multiple="multiple" value="" />
            <output id="list"></output>
            <small>
              <strong>
                <br>
                Hinweis: Es können <u>maximal 19</u> Dateien aufeinmal versendet werden! <br>Unterstützte Dateiformate: PDF, JPG und PNG
              </strong>
            </small>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-send" data-bs-dismiss="modal">Weiter</button>
            <button type="button" id="clearFiles">Inhalte löschen</button>
            <!--<button type="button" class="btn btn-primary">Save changes</button>-->
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

【讨论】:

  • 这很完美!谢谢!
  • 我还有一个问题@LouysPatriceBessette 如果我希望所有 PDF 文档都有一个特定的图像分配给它们,我应该执行以下操作:
  • if (!f.type.match('image.*')) { span.innerHTML = ['' ].join( ''); } else { span.innerHTML = ['' ].join(''); } 对吗?
  • 可能......它有效吗? -- 我会使用类而不是内联样式。这将使代码更具可读性。 ;)
  • 你知道吗?我爱你!效果很好!非常感谢@LouysPatriceBessette
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
相关资源
最近更新 更多