在前端开发中,经常需要处理文件上传功能。有时我们只需要获取用户选择文件的名称而不需要立即上传文件内容。本文将介绍3种在JavaScript中获取input上传文件名称的方法。
document.getElementById('fileInput').addEventListener('change', function(e) {
const fileName = e.target.files[0].name;
console.log('文件名:', fileName);
});
这是最常用的方法,通过File API获取文件对象,然后访问其name属性。
document.getElementById('fileInput').addEventListener('change', function() {
const fullPath = this.value;
const fileName = fullPath.split('\\').pop().split('/').pop();
console.log('文件名:', fileName);
});
这种方法通过解析input的value值来获取文件名,适用于不支持File API的旧浏览器。
document.getElementById('fileInput').addEventListener('change', function(e) {
const file = e.target.files[0];
const fileName = new URL(`file://${file.name}`).pathname.split('/').pop();
console.log('文件名:', fileName);
});
这种方法结合了URL API,可以更安全地处理文件名。
以上三种方法都可以有效获取input上传文件的名称,开发者可以根据项目需求和浏览器兼容性要求选择合适的方法。