Javascript - 如何从文件输入控件中提取文件名

发布于 2024-07-19 07:29:47 字数 160 浏览 4 评论 0原文

当用户在网页中选择文件时,我希望能够仅提取文件名。

我确实尝试了 str.search 函数,但当文件名如下所示时似乎会失败:c:\uploads\ilike.this.file.jpg

我们怎样才能只提取文件名而不提取扩展名呢?

When a user selects a file in a web page I want to be able to extract just the filename.

I did try str.search function but it seems to fail when the file name is something like this: c:\uploads\ilike.this.file.jpg.

How can we extract just the file name without extension?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

流殇 2024-07-26 07:29:47

要分割字符串 ({filepath}/{filename}) 并获取文件名,您可以使用如下内容:

str.split(/(\\|\/)/g).pop()

“pop 方法从数组中删除最后一个元素并返回该元素
对调用者的价值。”
Mozilla 开发者网络

示例:

来自:"/home /user/file.txt".split(/(\\|\/)/g).pop()

你得到:"file.txt"

To split the string ({filepath}/{filename}) and get the file name you could use something like this:

str.split(/(\\|\/)/g).pop()

"The pop method removes the last element from an array and returns that
value to the caller."
Mozilla Developer Network

Example:

from: "/home/user/file.txt".split(/(\\|\/)/g).pop()

you get: "file.txt"

戏蝶舞 2024-07-26 07:29:47

现在有一种更简单的方法:

var fileInput = document.getElementById('upload');   
var filename = fileInput.files[0].name;

Nowadays there is a much simpler way:

var fileInput = document.getElementById('upload');   
var filename = fileInput.files[0].name;
酷遇一生 2024-07-26 07:29:47

假设您的 的 id 为 upload 这应该可以解决问题:

var fullPath = document.getElementById('upload').value;
if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
    alert(filename);
}

Assuming your <input type="file" > has an id of upload this should hopefully do the trick:

var fullPath = document.getElementById('upload').value;
if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
    alert(filename);
}
杀お生予夺 2024-07-26 07:29:47

很简单

let file = $("#fileupload")[0].files[0]; 
file.name

Very simple

let file = $("#fileupload")[0].files[0]; 
file.name
极致的悲 2024-07-26 07:29:47

假设:

<input type="file" name="file1" id="theFile">

JavaScript 是:

var fileName = document.getElementById('theFile').files[0].name;

Assuming:

<input type="file" name="file1" id="theFile">

The JavaScript would be:

var fileName = document.getElementById('theFile').files[0].name;
故乡的云 2024-07-26 07:29:47

我假设您想删除所有扩展名,即 /tmp/test/somefile.tar.gzsomefile

使用正则表达式的直接方法:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

使用正则表达式和数组操作的替代方法:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];

I assume you want to strip all extensions, i.e. /tmp/test/somefile.tar.gz to somefile.

Direct approach with regex:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

Alternative approach with regex and array operation:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];
余厌 2024-07-26 07:29:47
var pieces = str.split('\\');
var filename = pieces[pieces.length-1];
var pieces = str.split('\\');
var filename = pieces[pieces.length-1];
半暖夏伤 2024-07-26 07:29:47

输入C:\path\Filename.ext
输出文件名

在 HTML 代码中,设置文件 onChange 值,如下所示...

<input type="file" name="formdata" id="formdata" onchange="setfilename(this.value)"/>

假设您的文本字段 ID 为“wpName”...

<input type="text" name="wpName" id="wpName">

JavaScript

<script>
  function setfilename(val)
  {
    filename = val.split('\\').pop().split('/').pop();
    filename = filename.substring(0, filename.lastIndexOf('.'));
    document.getElementById('wpName').value = filename;
  }
</script>

Input: C:\path\Filename.ext
Output: Filename

In HTML code, set the File onChange value like this...

<input type="file" name="formdata" id="formdata" onchange="setfilename(this.value)"/>

Assuming your textfield id is 'wpName'...

<input type="text" name="wpName" id="wpName">

JavaScript

<script>
  function setfilename(val)
  {
    filename = val.split('\\').pop().split('/').pop();
    filename = filename.substring(0, filename.lastIndexOf('.'));
    document.getElementById('wpName').value = filename;
  }
</script>
栩栩如生 2024-07-26 07:29:47

我刚刚做了我自己的版本。 我的函数可用于从中提取您想要的任何内容,如果您不需要全部,那么您可以轻松删除一些代码。

<html>
<body>
<script type="text/javascript">
// Useful function to separate path name and extension from full path string
function pathToFile(str)
{
    var nOffset = Math.max(0, Math.max(str.lastIndexOf('\\'), str.lastIndexOf('/')));
    var eOffset = str.lastIndexOf('.');
    if(eOffset < 0 && eOffset < nOffset)
    {
        eOffset = str.length;
    }
    return {isDirectory: eOffset === str.length, // Optionally: && nOffset+1 === str.length if trailing slash means dir, and otherwise always file
            path: str.substring(0, nOffset),
            name: str.substring(nOffset > 0 ? nOffset + 1 : nOffset, eOffset),
            extension: str.substring(eOffset > 0 ? eOffset + 1 : eOffset, str.length)};
}

// Testing the function
var testcases = [
    "C:\\blabla\\blaeobuaeu\\testcase1.jpeg",
    "/tmp/blabla/testcase2.png",
    "testcase3.htm",
    "C:\\Testcase4", "/dir.with.dots/fileWithoutDots",
    "/dir.with.dots/another.dir/"
];
for(var i=0;i<testcases.length;i++)
{
    var file = pathToFile(testcases[i]);
    document.write("- " + (file.isDirectory ? "Directory" : "File") + " with name '" + file.name + "' has extension: '" + file.extension + "' is in directory: '" + file.path + "'<br />");
}
</script>
</body>
</html>

将输出以下内容:

  • 名为“testcase1”的文件具有扩展名:“jpeg”位于目录:“C:\blabla\blaeobuaeu”
  • 名为“testcase2”的文件具有扩展名:“png”位于目录:“/tmp/blabla” '
  • 名为 'testcase3' 的文件具有扩展名:'htm' 位于目录:''
  • 名为 'Testcase4' 的目录具有扩展名:'' 位于目录:'C:'
  • 名为 'fileWithoutDots' 的目录具有扩展名:'' 是在目录中:'/dir.with.dots'
  • 名为 '' 的目录具有扩展名:'' 在目录中:'/dir.with.dots/another.dir'

使用 && nOffset+1 === str.length 添加到 isDirectory

  • 名称为“testcase1”的文件扩展名:“jpeg”位于目录:“C:\blabla\blaeobuaeu”
  • 文件包含名称“testcase2”的扩展名:“png”在目录中:“/tmp/blabla”
  • 名称为“testcase3”的文件的扩展名:“htm”在目录中:“
  • 名称为“Testcase4”的目录的扩展名:“是在目录中:'C:'
  • 名为 'fileWithoutDots' 的目录具有扩展名:'' 在目录中:'/dir.with.dots'
  • 名为 '' 的目录具有扩展名:'' 在目录中:'/dir.with。 dots/another.dir'

给定测试用例,您可以看到与此处提出的其他方法相比,该函数的工作相当稳健。

新手请注意 \\: \ 是转义字符,例如 \n 表示换行符,\ta 表示制表符。 为了能够写入 \n,您必须实际键入 \\n。

I just made my own version of this. My function can be used to extract whatever you want from it, if you don't need all of it, then you can easily remove some code.

<html>
<body>
<script type="text/javascript">
// Useful function to separate path name and extension from full path string
function pathToFile(str)
{
    var nOffset = Math.max(0, Math.max(str.lastIndexOf('\\'), str.lastIndexOf('/')));
    var eOffset = str.lastIndexOf('.');
    if(eOffset < 0 && eOffset < nOffset)
    {
        eOffset = str.length;
    }
    return {isDirectory: eOffset === str.length, // Optionally: && nOffset+1 === str.length if trailing slash means dir, and otherwise always file
            path: str.substring(0, nOffset),
            name: str.substring(nOffset > 0 ? nOffset + 1 : nOffset, eOffset),
            extension: str.substring(eOffset > 0 ? eOffset + 1 : eOffset, str.length)};
}

// Testing the function
var testcases = [
    "C:\\blabla\\blaeobuaeu\\testcase1.jpeg",
    "/tmp/blabla/testcase2.png",
    "testcase3.htm",
    "C:\\Testcase4", "/dir.with.dots/fileWithoutDots",
    "/dir.with.dots/another.dir/"
];
for(var i=0;i<testcases.length;i++)
{
    var file = pathToFile(testcases[i]);
    document.write("- " + (file.isDirectory ? "Directory" : "File") + " with name '" + file.name + "' has extension: '" + file.extension + "' is in directory: '" + file.path + "'<br />");
}
</script>
</body>
</html>

Will output the following:

  • File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
  • File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
  • File with name 'testcase3' has extension: 'htm' is in directory: ''
  • Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
  • Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
  • Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'

With && nOffset+1 === str.length added to isDirectory:

  • File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
  • File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
  • File with name 'testcase3' has extension: 'htm' is in directory: ''
  • Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
  • Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
  • Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'

Given the testcases you can see this function works quite robustly compared to the other proposed methods here.

Note for newbies about the \\: \ is an escape character, for example \n means a newline and \t a tab. To make it possible to write \n, you must actually type \\n.

请止步禁区 2024-07-26 07:29:47

这两个高度赞扬的答案实际上都没有提供“只提供没有扩展名的文件名”,而其他解决方案对于这样一个简单的工作来说代码太多了。

我认为这对于任何 JavaScript 程序员来说都应该是一句口头禅。 这是一个非常简单的正则表达式:

function basename(prevname) {
    return prevname.replace(/^(.*[/\\])?/, '').replace(/(\.[^.]*)$/, '');
}

首先,删除最后一个斜线之前的所有内容(如果存在)。

然后,删除最后一个句点之后的所有内容(如果有)。

它很简单,很强大,它完全实现了所要求的功能。 我错过了什么吗?

Neither of the highly upvoted answers actually provide "just the file name without extension" and the other solutions are way too much code for such a simple job.

I think this should be a one-liner to any JavaScript programmer. It's a very simple regular expression:

function basename(prevname) {
    return prevname.replace(/^(.*[/\\])?/, '').replace(/(\.[^.]*)$/, '');
}

First, strip anything up to the last slash, if present.

Then, strip anything after the last period, if present.

It's simple, it's robust, it implements exactly what's asked for. Am I missing something?

奶茶白久 2024-07-26 07:29:47

简单路径:

JQuery

$("#fileInputId").on("change", () => {
    alert($("#fileInputId")[0].files[0].name);
});

JavaScript

document.getElementById("fileInputId").onchange = function() {
   alert(document.getElementById("fileInputId").files[0].name)
};

Easy Path:

JQuery

$("#fileInputId").on("change", () => {
    alert($("#fileInputId")[0].files[0].name);
});

JavaScript

document.getElementById("fileInputId").onchange = function() {
   alert(document.getElementById("fileInputId").files[0].name)
};
一个人的夜不怕黑 2024-07-26 07:29:47
// HTML
<input type="file" onchange="getFileName(this)">

// JS
function getFileName(input) {
    console.log(input.files[0].name) // With extension
    console.log(input.files[0].name.replace(/\.[^/.]+$/, '')) // Without extension
}

如何删除扩展

// HTML
<input type="file" onchange="getFileName(this)">

// JS
function getFileName(input) {
    console.log(input.files[0].name) // With extension
    console.log(input.files[0].name.replace(/\.[^/.]+$/, '')) // Without extension
}

How to remove the extension

清音悠歌 2024-07-26 07:29:47
var path = document.getElementById('upload').value;//take path
var tokens= path.split('\\');//split path
var filename = tokens[tokens.length-1];//take file name
var path = document.getElementById('upload').value;//take path
var tokens= path.split('\\');//split path
var filename = tokens[tokens.length-1];//take file name
可爱咩 2024-07-26 07:29:47

以上答案都不适合我,这是我的解决方案,它使用文件名更新禁用的输入:

<script type="text/javascript"> 
  document.getElementById('img_name').onchange = function () {
  var filePath = this.value;
    if (filePath) {
      var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
      document.getElementById('img_name_input').value = fileName;
    }
  };
</script>

None of the above answers worked for me, here is my solution which updates a disabled input with the filename:

<script type="text/javascript"> 
  document.getElementById('img_name').onchange = function () {
  var filePath = this.value;
    if (filePath) {
      var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
      document.getElementById('img_name_input').value = fileName;
    }
  };
</script>
飘逸的'云 2024-07-26 07:29:47

如果你使用 jQuery 那么

$("#fileupload").val();

If you are using jQuery then

$("#fileupload").val();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文