我正在用VS2012和Javascript开发一个地铁应用程序

我想重置我的文件输入的内容:

<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />

我该怎么做呢?


当前回答

<input type="file" id="mfile" name="mfile">
<p>Reset</p>

<script>
$(document).ready(function(){
$("p").click(function(){

            $("#mfile").val('');
            return false;

    });
});

其他回答

jQuery的解决方案:

    $('input').on('change',function(){
                $(this).get(0).value = '';
                $(this).get(0).type = '';
                $(this).get(0).type = 'file';
            });

你不能重置,因为它是一个只读文件。你可以克隆它来解决这个问题。

特别是对于Angular来说

document.getElementById('uploadFile').value = "";

会工作,但是如果你使用Angular呢 它会说“属性‘value’在类型‘HTMLElement’.any上不存在”

document.getElementById()返回不包含value属性的HTMLElement类型。因此,将它转换为HTMLInputElement

(<HTMLInputElement>document.getElementById('uploadFile')).value = "";

额外的:-

然而,我们不应该在angular中使用DOM操作(document.xyz())。

为此,angular提供了@ViewChild、@ViewChildren等,分别是document.querySelector()、document.queryselectorAll()。

连我都没读过。最好关注专家的博客

通过这个link1和link2

另一种解决方案(不选择HTML DOM元素)

如果你在输入中添加了'change'事件监听器,那么在javascript代码中你可以调用(对于某些特定的条件):

event.target.value = '';

例如在HTML中:

<input type="file" onChange="onChangeFunction(event)">

在javascript中:

onChangeFunction(event) {
  let fileList = event.target.files;
  let file = fileList[0];
  let extension = file.name.match(/(?<=\.)\w+$/g)[0].toLowerCase(); // assuming that this file has any extension

  if (extension === 'jpg') {
    alert('Good file extension!');
  }
  else {
    event.target.value = '';
    alert('Wrong file extension! File input is cleared.');
  }

我在这里错过了另一个解决方案(2021年): 我使用FileList与文件输入交互。

因为没有办法创建FileList对象,所以我使用DataTransfer,它带来了干净的FilleList。

我用:

  file_input.files=new DataTransfer().files  

在我的例子中,这非常适合,因为我只通过FileList与封装的文件输入元素进行交互。