Reputation: 1023
I've a code that implements that if the user chooses a file that is not jpg, jpeg or png it displays an error message.
async function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
fileContent = await readFile(file);
}else{
alert("Only jpg, jpeg or png allowed");
}
}
This is called from this:
<input type="file" align="center" accept=".jpg,.jpeg,.png" onchange="read(this)"/>
Problem is that regardless the file what was taken it changes the text of the file input to the selected file wether it was an accepted type or not. Although fileContent continues to be empty or has the last value for the last selected accpted file, the file shown is another one.
How to avoid this behavior so if an accepted file is the one chosen the text for the choosen file isn't changed?
Upvotes: 0
Views: 50
Reputation: 73926
You can prevent the input file text from changing by just setting the input value to null
like:
async function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
fileContent = await readFile(file);
}else{
alert("Only jpg, jpeg or png allowed");
input.value = null;
}
}
DEMO:
async function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//fileContent = await readFile(file);
alert("Valid file selected!");
}else{
alert("Only jpg, jpeg or png allowed");
input.value = null;
}
}
<input type="file" align="center" accept=".jpg,.jpeg,.png" onchange="read(this)"/>
<br/>
<p>Please select a non-image file like a pdf for testing.</p>
Upvotes: 1