javascript 仅从 Internet Explorer 上的文件输入获取文件名

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

Get only file name from file input on internet explorer

javascripthtml

提问by user937450

I need to return only the file name from an HTML input file.

我只需要从 HTML 输入文件中返回文件名。

<input type="file" id="whatever" />

The JavaScript code im using to get the name of the file is:

我用来获取文件名的 JavaScript 代码是:

document.getElementById("whatever").value;

In firefox it gives only the file name which is what I want, but in IE I get the full path.

在 Firefox 中,它只给出了我想要的文件名,但在 IE 中我得到了完整路径。

I think that string manipulation is the only way to get the name.

我认为字符串操作是获取名称的唯一方法。

What would be the easiest/shortest way to get only the name (extension too) in JavaScript? Thanks.

在 JavaScript 中仅获取名称(扩展名)的最简单/最短方法是什么?谢谢。

回答by karthick

You can try this

你可以试试这个

var path = document.getElementById("whatever").value;
var fileName = path.match(/[^\/\]+$/);
console.log(fileName);

回答by Sandeep

I hope this works.

我希望这有效。

var fullFileName = document.getElementById("whatever").value;
var fileName = fullFileName.substr(fullFileName.lastIndexOf("\")+1, fullFileName.length);

Here is the fiddle for that Fiddle

这是那个小提琴的小提琴

回答by Explosion Pills

var path = document.getElementById("whatever").value;
var filename = path.substring(path.lastIndexOf("/") + 1);

This will give you everything after the last /, but is also compatible with a lack of /s. In case you also need to deal with \as the lovely path separator, you can always use this first:

这将为您提供 last 之后的所有内容/,但也与缺少/s兼容。如果您还需要处理\可爱的路径分隔符,您可以先使用它:

path.replace(/\/g, "/")