簡體   English   中英

如何從HTML5 FileReader中的“輸入類型”清除以前的文件

[英]How to clear a previous file from a 'input type' in HTML5 FileReader

我有一個文件輸入:

<img id="uploadPreview">
   <div id="changeImage">Change</div>
<div id="customImage">
   <input type="file" id="myfile" multiple style="display:none" onchange="PreviewImage();" />
   <div class='upload blank' id="add-image"></div>
</div>

功能如下:

var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("myfile").files[0]);

oFReader.onload = function (oFREvent) {
    document.getElementById("uploadPreview").src = oFREvent.target.result;
};

function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("myfile").files[0]);
        $("#uploadPreview").removeClass('hide'); //for manipulating something in the dom
        $('#changeImage').removeClass('hide'); //for manipulating something in the dom
        $("#customImage").addClass('hide'); //these are for manipulating something in the dom

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };

一切正常。 現在,我有一個更改按鈕。 我想如果有人單擊它,那么以前上傳的文件詳細信息將消失。 該函數如下所示:

$('#changeImage').click(function(){
  $('#uploadPreview').addClass('hide');
  $('#customImage').removeClass('hide');
  //here I want to remove/clear the details about the already previous uploaded file in the 'file-input'. So the same image can be shown if someone clicks it for once again. 

});

你能幫上忙嗎?

如果您希望將數據保留在其他表單字段中,則可以使用

的HTML

    <input type='file' id='yourid' />

jQuery的

    $('#yourid').val('');

這將從輸入標簽中清除您上傳的文件

如果將文件輸入放在<form>標記內,則可以使用內置的.reset()方法。

HTML:

<img id="uploadPreview">
   <div id="changeImage">Change</div>
<div id="customImage">
   <form id="fileform">
      <input type="file" id="myfile" multiple style="display:none" onchange="PreviewImage();" />
   </form>
   <div class='upload blank' id="add-image"></div>
</div>

JS:

$('#changeImage').click(function(){
   $('#uploadPreview').addClass('hide');
   $('#customImage').removeClass('hide');
   // Reset the form
   $("#fileform")[0].reset();
});

沒有jQuery的JS:

var resetButton = document.getElementById('resetButton');
var fileInput = document.getElementById('fileInput');
var form = document.getElementById('form');

resetButton.addEventListener('click', function () {
    // resetting the file input only
    fileInput.value = null;

    // alternatively: resetting the entire form (works in older browsers too)
    form.reset();
});

React我在基於chrome的瀏覽器上輸入文件時遇到了這個問題。 我使用value=""autoComplete={"new-password"}的組合修復它

<input
  value=""
  type="file"
  autoComplete={"new-password"}
  onChange={e => pickHandler(e)}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM