Here’s an example how you can get file-name from file input in Javascript:
Code of index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./script.js"></script> </head> <body> <div> <label for="file">Select file</label> <input type="file" name="file" id="file"> </div> </body> </html>
Code of script.js:
window.onload = function() { document.getElementById('file').addEventListener('change', getFileName); } const getFileName = (event) => { const files = event.target.files; const fileName = files[0].name; console.log("file name: ", fileName); }
Explanation:
In the above code, We are adding an event listener to the input element which detects the changes and executes the getFileName method.
In the getFileName method, using the event object of javascript, we can get selected file objects. If we want to get file-name then we can use the name property of the selected file object.
Here’s an example for multiple file inputs in single html file,
Code of index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./script.js"></script> </head> <body> <div> <label for="file">Select file 1:</label> <input type="file" name="file" class="file"> </div> <div> <label for="file">Select file 2:</label> <input type="file" name="file" class="file"> </div> <div> <label for="file">Select file 3:</label> <input type="file" name="file" class="file"> </div> </body> </html>
Code of script.js:
window.onload = function() { const fileCollection = document.getElementsByClassName('file'); for(let fileInput of fileCollection) { fileInput.addEventListener('change', getFileName); } } const getFileName = (event) => { const files = event.target.files; const fileName = files[0].name; console.log("file name: ", fileName); }
Now for multiple file inputs, We just have to use class selector instead of id selector and iterate the collection returned by the getElementsByClassName() method.
Similar to a single file logic, for each input element, add the event listener which detects the changes and we will get file name in the getFileName method.