0

I follow Javascript - How to extract filename from a file input control and I have few problems with getting file name from input/upload file. I use this code to get file name from input file

var fileInput = document.getElementById('upload_file').files[0].name;

But when I change with another file, I still get my old file name and I need to refresh my browser to get latest file name. How to fix something like this?

<html>
    <head>
        <meta charset="utf-8">
        <script src="http://code.jquery.com/jquery-3.3.1.js"></script>
    </head>
    <body>
        <input type="file" id="upload_file">
        <br>
        <h1 id="nama_file"></h1>
        <script>
            var fileInput = document.getElementById('upload_file').files[0].name;   
            //var filename = fileInput.files[0].name;
            console.log(fileInput);
            document.getElementById('nama_file').innerText = fileInput;
        </script>
    </body>
</html>
Ivar
  • 6,138
  • 12
  • 49
  • 61
Ade Guntoro
  • 99
  • 1
  • 2
  • 9

2 Answers2

0

You can add a event on every load and change the inner text of 'name_file' accordingly.

<html>
    <head>
        <meta charset="utf-8">
        <script src="http://code.jquery.com/jquery-3.3.1.js"></script>
    </head>
    <body>
        <input type="file" id="upload_file">
        <br>
        <h1 id="nama_file"></h1>
        <script>
            var fileInput = document.getElementById('upload_file').files[0].name;   
            fileInput.addEventListener('change', () => {
             document.getElementById('nama_file').innerText = fileInput;
            });
            console.log(fileInput);
        </script>
    </body>
</html>
Pankaj Manali
  • 668
  • 6
  • 15
  • `Uncaught TypeError: Cannot read property 'name' of undefined`. Why `.name` error ? – Ade Guntoro Apr 23 '18 at 15:45
  • Because we are trying to get that property before we have uploaded the file. We need to add a check. For a quick fix: var fileInput = document.getElementById('upload_file').files[0] ? document.getElementById('upload_file').files[0].name : ""; – Pankaj Manali Apr 24 '18 at 05:58
0

You need an event:

var filename = document.getElementById('filename');
document.getElementById('upload_file').addEventListener('change', function(e) {
  filename.innerText = e.target.files[0].name;
});
<input type="file" id="upload_file">
<br>
<h1 id="filename"></h1>
Amthieu
  • 154
  • 1
  • 9