How to get file name when user select a file via <input type="file" />? How to get file name when user select a file via <input type="file" />? javascript javascript

How to get file name when user select a file via <input type="file" />?


You can get the file name, but you cannot get the full client file-system path.

Try to access to the value attribute of your file input on the change event.

Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:\fakepath\myfile.ext" and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

document.getElementById('fileInput').onchange = function () {  alert('Selected file: ' + this.value);};


You can use the next code:

JS

    function showname () {      var name = document.getElementById('fileInput');       alert('Selected file: ' + name.files.item(0).name);      alert('Selected file: ' + name.files.item(0).size);      alert('Selected file: ' + name.files.item(0).type);    };

HTML

<body>    <p>        <input type="file" id="fileInput" multiple onchange="showname()"/>    </p>    </body>


just tested doing this and it seems to work in firefox & IE

<html>    <head>        <script type="text/javascript">            function alertFilename()            {                var thefile = document.getElementById('thefile');                alert(thefile.value);            }        </script>    </head>    <body>        <form>            <input type="file" id="thefile" onchange="alertFilename()" />            <input type="button" onclick="alertFilename()" value="alert" />        </form>    </body></html>