How to get selected file name from input type file using jQuery?

How to get selected file name from input type file using jQuery?

Asked on November 2, 2018 in jQuery.
Add Comment


  • 2 Answer(s)

      The jQuery change() method is the best way to get the file name selected by the HTML form control <input type=”file”>.

    For example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>jQuery Get Selected File Name</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function()
    {
        $('input[type="file"]').change(function(e)
    {
          var fileName = e.target.files[0].name;
          alert('The file "' + fileName + '" has been selected.');
        });
       });
    </script>
    </head>
    <body>
      <form>
        <input type="file">
      </form>
    </body>
    </html>
    
    Answered on November 2, 2018.
    Add Comment
    var filename = $('input[type=file]').val().split('\\').pop();

    or you could just do (because it’s always C:\fakepath that is added for security reasons):

    var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.