Reputation: 1180
Because my users have to select a file from a folder with a lot of files in it, I would like to add a filter to the open file dialog that is invoked from an input file field. I understand that <input type="file">
field allows filtering by file extensions like this:
<input accept=".txt" type="file" />
But, is it possible to set a filter to a specific filename, too?
In a C# winform app I would just set the Filter
property of a openFileDialog
to Foo|bar.txt
and it would only show me bar.txt
files.
Upvotes: 2
Views: 1054
Reputation: 1084
I don't think there's any attribute for it in HTML but you can do it by using javascript.
I have created a basic example. Here I am accepting only the filename say specific-filename
. You can set it according to your needs.
let file = document.getElementById('file');
file.addEventListener('change', (e)=> {
const fullPath = e.target.value;
const filename = fullPath.replace(/^.*[\\\/]/, '').split('.')[0];
console.log(filename); //the name of your file
if(filename!=='specific-filename') {
e.target.value=''; // this resets the value of input field
}
});
<div class="container">
<input type="file" id="file">
</div>
If you have a form, you can do it similarly at the time of form submission and not allowing the submission unless filename matched. Here, I have intercepted the process onchange
of input field
Hope it helps!
Upvotes: 1