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

后端 未结 14 681
醉话见心
醉话见心 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:34
    var filename=location.href.substr(location.href.lastIndexOf("/")+1);
    alert(filename);
    
    0 讨论(0)
  • 2020-11-27 10:37

    We can also remove it using match

    var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
    $('#file-name').val(fileName);
    
    0 讨论(0)
  • 2020-11-27 10:38

    How about something like this?

    var pathArray = $('input[type=file]').val().split('\\');
    alert(pathArray[pathArray.length - 1]);
    
    0 讨论(0)
  • 2020-11-27 10:40

    This alternative seems the most appropriate.

    $('input[type="file"]').change(function(e){
            var fileName = e.target.files[0].name;
            alert('The file "' + fileName +  '" has been selected.');
    });
    
    0 讨论(0)
  • 2020-11-27 10:43

    Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.

    To get just the filename portion of a string, you can use split()...

    var file = path.split('\\').pop();
    

    jsFiddle.

    ...or a regular expression...

    var file = path.match(/\\([^\\]+)$/)[1];
    

    jsFiddle.

    ...or lastIndexOf()...

    var file = path.substr(path.lastIndexOf('\\') + 1);
    

    jsFiddle.

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

    Get path work with all OS

    var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
    

    Example

    C:\fakepath\filename.doc 
    /var/fakepath/filename.doc
    

    Both return

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