How to get the fileName in javascript from input file tag in IE browser

前端 未结 3 468
终归单人心
终归单人心 2020-12-18 03:57

I have done this in jQuery, to get filename from input file tag, With jQuery it works perfectly.

相关标签:
3条回答
  • 2020-12-18 04:21

    I found the problem to be in getElementsByTagName method, you use this when you have a group of elements with the same tag name.

    Try this code below, it works

    //HTML
    <input id="inp" type="file" />
    
    
    // JavaScript
    document.getElementById('inp').addEventListener('change',prepareUpload,false);
    
    function prepareUpload(event)
    {
      var files = event.target.files;
      var fileName = files[0].name;
      alert(fileName);
    }
    

    Below is the code if you want to do it for more than one element

    <body>
    <input type="file" class="input"/>
    <input type="file" class="input"/>
    <input type="file" class="input"/>
    <input type="file" class="input"/>
    
    <script>
    var inputArray = document.getElementsByClassName('input');
    
    for(var i = 0; i < inputArray.length; i++){
        inputArray[i].addEventListener('change',prepareUpload,false);
    };
    
    function prepareUpload(event)
    {
        var files = event.target.files;
        var fileName = files[0].name;
        alert(fileName);
    }
    </script>
    </body>
    
    0 讨论(0)
  • 2020-12-18 04:24

    This will work

    var fileName = $("input[type='file']").val().split('/').pop().split('\\').pop();
    
    0 讨论(0)
  • 2020-12-18 04:28

    The code above is correct for all but IE simply because IE doesn't like event.target - you need event.srcElement: https://developer.mozilla.org/en-US/docs/Web/API/Event/srcElement

    So something like this should sort that out:

    var files;
    
    if (window.navigator.userAgent.indexOf("MSIE ") > 0) ? 
        files = event.srcElement.files :
        files = event.target.files;
    

    I couldn't make that work in the "Run Snippet" thing SO has, though, so here's how you can just get it using another button:

    document.getElementById('myBtn').addEventListener('click', function() { 
       doUpload(); 
    });
    
    function doUpload()
    {
        var myFile = myInput.files[0];
        // can also use var myFile = document.querySelector('input').files[0];
        var fileName = myFile.name;
        alert(fileName);
    }
    <input id="myInput" type="file" />
    <button id="myBtn">Try Me</button>

    0 讨论(0)
提交回复
热议问题