How to Get File Name from Upload Form Using jQuery

2019-04-04 19:24发布

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.

3条回答
够拽才男人
2楼-- · 2019-04-04 19:50

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
});
查看更多
Emotional °昔
3楼-- · 2019-04-04 19:56

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

see: Getting the last element of a split string array

查看更多
倾城 Initia
4楼-- · 2019-04-04 20:13

get file name when uploading using jquery

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

查看更多
登录 后发表回答