Javascript 使用 jQuery 获取文件输入的选定文件名而不带路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6365858/
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-23 21:26:22  来源:igfitidea点击:

Use jQuery to get the file input's selected filename without the path

javascriptjquerygetfilenames

提问by marky

I used this:

我用过这个:

$('input[type=file]').val()

to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.

选择文件名,但它返回完整路径,如“C:\fakepath\filename.doc”。“fakepath”部分实际上在那里 - 不确定它是否应该存在,但这是我第一次使用文件上传的文件名。

How can I just get the file name (filename.doc)?

我怎样才能得到文件名(filename.doc)?

回答by manji

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

or you could just do (because it's always C:\fakepaththat is added for security reasons):

或者你可以这样做(因为它总是C:\fakepath出于安全原因添加):

var filename = $('input[type=file]').val().replace(/C:\fakepath\/i, '')

回答by Diego Cotini

You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):

你只需要执行下面的代码。第一个 [0] 是访问 HTML 元素,第二个 [0] 是访问文件上传的第一个文件(我包含了一个验证,以防没有文件):

    var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";

回答by alex

Chrome returns C:\fakepath\...for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.

ChromeC:\fakepath\...出于安全原因返回- 网站应该无法获取有关您计算机的信息,例如您计算机上文件的路径。

To get just the filename portion of a string, you can use split()...

要仅获取字符串的文件名部分,您可以使用split()...

var file = path.split('\').pop();

jsFiddle.

js小提琴

...or a regular expression...

...或正则表达式...

var file = path.match(/\([^\]+)$/)[1];

jsFiddle.

js小提琴

...or lastIndexOf()...

……或者lastIndexOf()……

var file = path.substr(path.lastIndexOf('\') + 1);

jsFiddle.

js小提琴

回答by Kotzilla

Get path work with all OS

获取所有操作系统的路径

var filename = $('input[type=file]').val().replace(/.*(\/|\)/, '');

Example

例子

C:\fakepath\filename.doc 
/var/fakepath/filename.doc

Both return

两者都返回

filename.doc
filename.doc

回答by bartlss

Here is how I do it, it works pretty well.

这是我的做法,效果很好。

In your HTML do:

在你的 HTML 中做:

<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />

Then in your js file create a simple function:

然后在你的 js 文件中创建一个简单的函数:

function fileSelect(id, e){
    console.log(e.target.files[0].name);
}

If you're doing multiple files, you should also be able to get the list by looping over this:

如果您正在处理多个文件,您还应该能够通过循环获取列表:

e.target.files[0].name

回答by vafrcor

maybe some addition for avoid fakepath:

也许是为了避免假路径的一些补充:

var fileName = $('input[type=file]').val();
var clean=fileName.split('\').pop(); // clean from C:\fakepath OR C:\fake_path 
alert('clean file name : '+ fileName);

回答by Bertrand Marron

How about something like this?

这样的事情怎么样?

var pathArray = $('input[type=file]').val().split('\');
alert(pathArray[pathArray.length - 1]);

回答by GolezTrol

Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\")to split the string to an array?

它必须是jquery吗?或者你可以使用 JavaScript 的原生yourpath.split("\\")将字符串拆分为数组吗?

回答by Azhar Shahazad

Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileNamemethod to get the file name only for IE browsers

从控件中获取第一个文件,然后获取文件名,Chrome 上会忽略文件路径,也会对 IE 浏览器进行路径修正。在保存文件时,您必须使用System.io.Path.GetFileName方法来获取仅适用于 IE 浏览器的文件名

var fileUpload    = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0); 
var files         =  fileUpload.files; 
var mediafilename = ""; 

for (var i = 0; i < files.length; i++) { 
  mediafilename = files[i].name; 
} 

回答by real vishal

<script type="text/javascript">

    $('#upload').on('change',function(){
       // output raw value of file input
       $('#filename').html($(this).val().replace(/.*(\/|\)/, '')); 

        // or, manipulate it further with regex etc.
        var filename = $(this).val().replace(/.*(\/|\)/, '');
        // .. do your magic

        $('#filename').html(filename);
    });
</script>