Use jQuery to get the file input's selected filename without the path

后端 未结 14 687
醉话见心
醉话见心 2020-11-27 10:02

I used this:

$(\'input[type=file]\').val()

to get the file name selected, but it returned the full path, as in \"C:\\fakepath\\filename.doc

相关标签:
14条回答
  • 2020-11-27 10:48

    Here is how I do it, it works pretty well.

    In your HTML do:

    <input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
    

    Then in your js file create a simple function:

    function fileSelect(id, e){
        console.log(e.target.files[0].name);
    }
    

    If you're doing multiple files, you should also be able to get the list by looping over this:

    e.target.files[0].name
    
    0 讨论(0)
  • 2020-11-27 10:49
    <script type="text/javascript">
    
        $('#upload').on('change',function(){
           // output raw value of file input
           $('#filename').html($(this).val().replace(/.*(\/|\\)/, '')); 
    
            // or, manipulate it further with regex etc.
            var filename = $(this).val().replace(/.*(\/|\\)/, '');
            // .. do your magic
    
            $('#filename').html(filename);
        });
    </script>
    
    0 讨论(0)
  • 2020-11-27 10:50

    maybe some addition for avoid fakepath:

    var fileName = $('input[type=file]').val();
    var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path 
    alert('clean file name : '+ fileName);
    
    0 讨论(0)
  • 2020-11-27 10:57

    You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):

        var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
    
    0 讨论(0)
  • 2020-11-27 10:59

    Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?

    0 讨论(0)
  • 2020-11-27 10:59

    Here you can call like this Let this is my Input File control

      <input type="file" title="search image" id="file" name="file" onchange="show(this)"  />
    

    Now here is my Jquery which get called once you select the file

    <script type="text/javascript">
        function show(input) {
            var fileName = input.files[0].name;
            alert('The file "' + fileName + '" has been selected.');               
                }
    
    </script>
    
    0 讨论(0)
提交回复
热议问题