Abaij
Abaij

Reputation: 873

How to Get File Name from Upload Form Using jQuery?

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.

Upvotes: 11

Views: 44903

Answers (3)

ujjal
ujjal

Reputation: 235

get file name when uploading using jquery

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

Upvotes: 2

Mike Mackintosh
Mike Mackintosh

Reputation: 14237

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
});

Upvotes: 4

Nathan Hase
Nathan Hase

Reputation: 659

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

see: Getting the last element of a split string array

Upvotes: 7

Related Questions