Javascript - 如何从文件输入控件中提取文件名 [英] Javascript - How to extract filename from a file input control
本文介绍了Javascript - 如何从文件输入控件中提取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户在网页中选择文件时,我希望能够仅提取文件名.
When a user selects a file in a web page I want to be able to extract just the filename.
我确实尝试过 str.search 函数,但是当文件名是这样的时它似乎失败了:c:uploadsilike.this.file.jpg.
I did try str.search function but it seems to fail when the file name is something like this: c:uploadsilike.this.file.jpg.
如何只提取没有扩展名的文件名?
How can we extract just the file name without extension?
推荐答案
假设您的 <input type="file" > 的 id 为 upload 这应该希望能成功:
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);
}
这篇关于Javascript - 如何从文件输入控件中提取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文