我有一个用于单个图像文件的输入文件上传字段:
<input type="file" id="imageupload" />
要访问所选图像文件的名称,我们使用
var fname = $("#imageupload")[0].files[0].name;
我不知道为什么在$("#imageupload")
之后使用[0]
与多个文件上传字段类似
<input type="file" id="imageupload" multiple />
我们使用(循环)
var file_name = $("#imageupload")[0].files[i].name;
任何人都可以澄清我对以下内容的概念:
$("#imageupload")[0]
文件[0]
文件[i]
最佳答案
$("#imageupload")[0]
基本上,我们不需要使用括号,因为在使用 ID 选择器时,在理想情况下,应该只有一个元素与给定 ID 匹配。我们在这里使用它只是为了确保不会发生错误。您可以删除 [0]
万一您的网站中恰好有一个元素具有该 ID。像这样:
var fname = $("#imageupload").prop('files')[0].name;
// or
var fname = document.getElementById('fileItem').files[0].name //without jQuery
这是演示:https://codesandbox.io/s/kx5q2x24xv
files[0] and files[i]
files
这里称为FileList
对象,并且:
An object of this type is returned by the files property of the HTML element; this lets you access the list of files selected with the
<input type="file">
element.
换句话说:
All element nodes have a files array on them which allows access to the items in this list.
我们使用括号和索引来访问该数组的特定元素。
此示例迭代用户使用输入元素选择的所有文件:
// fileInput is an HTML input element: <input type="file" id="myfileinput" multiple>
var fileInput = document.getElementById("myfileinput");
// files is a FileList object (similar to NodeList)
var files = fileInput.files;
var file;
// loop through files
for (var i = 0; i < files.length; i++) {
// get item
file = files.item(i);
//or
file = files[i];
alert(file.name);
}
了解更多信息:FileList
关于javascript - 在 JavaScript 中访问输入文件上传字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638988/