jQuery 如何使用jQuery从上传表单获取文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7500994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:56:03  来源:igfitidea点击:

How to Get File Name from Upload Form Using jQuery?

jqueryuploadfilenames

提问by Abaij

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.

我想使用 jQuery 获取上传文件的文件名。但问题是,我得到了假路径和文件名,而不仅仅是文件名。这是我的表格。

<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

而 jQuery 是这样的

$(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.

我使用 Chrome 并在警告框中得到了这个。假设我选择名为 filename.jpg 的文件。

C:\fakepath\filename.jpg

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

我怎样才能只得到文件名?感谢您的帮助。

回答by Nathan Hase

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

用“\”分割文件路径字符串并使用结果数组中的最后一项。

see: Getting the last element of a split string array

请参阅:获取拆分字符串数组的最后一个元素

回答by Mike Mackintosh

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

回答by ujjal

get file name when uploading using jquery

使用jquery上传时获取文件名

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

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