11

I want to get the file name of the uploaded file using jQuery. But the problem, I got the fake path and file name, instead of the file name only. This is my form.

<form action="" method="post">
   <input type="file" name="uploadFile" id="uploadFile" /> 
   <input type="submit" name="submit" value="Upload" id="inputSubmit" />
</form>

And the jQuery is like this

$(document).ready(function(){
    $('#inputSubmit').click(function(){
      alert($('#uploadFile').val());
    });
});

I use Chrome and got this in the alert box. Let's say I choose file named filename.jpg.

C:\fakepath\filename.jpg

How can I get only the file name? Thank you for your help.

Abaij
  • 853
  • 2
  • 18
  • 34

3 Answers3

7

Split the filepath string with "\" and use the last item in the resulting array.

see: Getting the last element of a split string array

Community
  • 1
  • 1
Nathan Hase
  • 649
  • 4
  • 11
4

You can also do:

$('#uploadFile').prop("files")['name'];

If it's a multiple file input, do:

$.each($('#uploadFile').prop("files"), function(k,v){
    var filename = v['name'];

    // filename = "blahblah.jpg", without path
});
Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
2

get file name when uploading using jquery

var filename = $('input[type=file]').val().split('\').pop();

Flexo
  • 87,323
  • 22
  • 191
  • 272
ujjal
  • 225
  • 4
  • 8