How to clear a previous file from a 'input type' in HTML5 FileReader
If you put your file input inside a <form>
tag you can use the built in .reset()
method.
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();
});
JS without jQuery:
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();
});
If you wish to keep data in other form fields, you can use
HTML
<input type='file' id='yourid' />
jQuery
$('#yourid').val('');
this will clear your uploaded file from input tag
In React
I experienced this issue for file inputs on chrome-based browsers. I fixed it with a combination of value=""
and autoComplete={"new-password"}
<input
value=""
type="file"
autoComplete={"new-password"}
onChange={e => pickHandler(e)}
/>