如何使用 JavaScript 或 JQuery 从输入类型=文件 html 元素获取文件名
How to get the filename from input type=file html element using JavaScript or JQuery?
在谷歌浏览器浏览器中,我已经尝试了几种方式+以下方法,但没有一种给我附加的文件名的值,验证后我将提交文件。但总是找不到它的未定义或 val((。
如何解决?
console.log($("input[name='attachment[]']"));
/* Output:
[
<input type="file" name="attachment[]" id="attachment">
,
<input type="file" name="attachment[]" id="attachment">
,
<input type="file" name="attachment[]" id="attachment">
]
*/
$.each($("input[name='attachment[]']"), function(i,v) {
console.log(i);
console.log(v); //v.val() does not exist... even uploaded a file and showing file
});
/* Output:
0
<input type="file" name="attachment[]" id="attachment">
1
<input type="file" name="attachment[]" id="attachment">
2
<input type="file" name="attachment[]" id="attachment">
*/
return false;
这应该有效:
$("input[name='attachment[]']").each(function() {
var fileName = $(this).val().split('/').pop().split('''').pop();
console.log(fileName);
});
您无法获取文件的完整路径,因为它取决于您使用的浏览器。输入文件的唯一常见跨浏览器值是文件名。
我会建议类似于以下内容:
$('input:file').change(
function(e){
console.log(e.target.files[0].name);
});
JS小提琴演示。
如果您允许使用 multiple
属性上传多个文件,则获取每个名称:
$('input:file').change(
function(e){
var f = e.target.files,
len = f.length;
for (var i=0;i<len;i++){
console.log(f[i].name);
}
});
JS小提琴演示。
注意:在当前的浏览器版本中,f[i].fileName
应f[i].name
。
<input type=file>
元素有一个零索引的 FileList,通过其成员变量 files
访问。
您可以通过查询选择器访问该列表:
document.querySelector('input[type=file]').files
您可以使用点表示法访问文件名:
document.querySelector('input[type=file]').files[0].name
应该注意的是,在Chrome 53,Firefox 49和FileAPI的当前W3C规范中,files
是一个类似数组的列表,而不是一个实际的数组。您可以通过每个文件对象的索引访问每个文件对象,但如果不先将列表转换为数组,您将无法访问任何数组原型。
for
<input type="file" mutiple onchange="getSongs(this.files)"/>
用
function getSongs(files){
...
for(var i = 0; i < files.length; i++){
file=files[i];
filename=file.fileName;
}
}
如果输入仅用于单个文件,则只需使用 name 属性
$("type=['file']").attr('name');
相关文章:
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 将HTML表格导出到excel时,无法将数据加载到excel文件中
- 导入jQuery脚本获胜'我不处理html文件
- 生成pdf或其他非html文件时的错误处理
- 从HTML调用typescript文件中的函数
- 使用metro-uiJS对话框调用其他文件html
- 使用选项卡导航到不同的html文件(html、JavaScript)
- 使用 socket.io 时如何发送文件(html,js,css和资源)
- 采购<p>从.txt文件.HTML
- 包含的html中的类无法访问父文件html中的函数
- 重新加载链接文件 HTML
- 如何使用 JavaScript 或 JQuery 从输入类型=文件 html 元素获取文件名
- Angularjs + 指令文件 html 内容点击事件在 js 文件中不起作用
- 如何直接从网页读取/写入本地文件 (html)
- jQuery加载txt文件.html()
- 指定简单配置文件HTML或javascript的最佳方式是什么
- Angular将所有头文件html提取到一个文件中
- 想要部分上传大文件.HTML/PHP
- AJAX -上传文件(HTML 5) &PHP