Here’s an example how you can get file name using FileReader constructor in Javascript:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./script.js"></script> </head> <body> <main> <div> <label for="file">Select file</label> <input type="file" name="file" id="file"> </div> <button onclick="uploadFile()">Upload</button> </main> </body> </html>
const uploadFile = () => { const file = document.getElementById("file").files[0]; const reader = new FileReader(); reader.onload = () => { console.log(reader.fileName); // file name }; // set file name for reader; reader.fileName = file.name; // Read the file reader.readAsDataURL(file); }
After selecting the file, when you click on the upload button, the uploadFile method will be executed.
Inside the method, we are storing the selected file inside the file variable and we are providing the file variable to FileReader.
And finally, inside the onload event handler of FileReader, We can get the name of the file.
Example for multi file input:
Code of index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./script.js"></script> </head> <body> <main> <div> <label for="file">Select file</label> <input type="file" name="file" id="file" multiple> </div> <button onclick="uploadFile()">Upload</button> </main> </body> </html>
Code of script.js
const uploadFile = () => { const files = document.getElementById("file").files; for(const file of files) { const reader = new FileReader(); reader.onload = () => { console.log(reader.fileName); // file name }; // set file name for reader; reader.fileName = file.name; // Read the file reader.readAsDataURL(file); } }
Compared to the previous example, for multi file input, we just have to iterate a list of files, and then we are providing individual file objects into FileReader.