Javascript 仅使用 File 对象选择单个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12360190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Single file select only using File object
提问by user3357963
MSDN has an example hereof the File object which allows multiple files to be selected
MSDN这里有一个File 对象的例子,它允许选择多个文件
<!DOCTYPE html>
<html>
<head>
<title>Acquiring File Information</title>
<style type="text/css">
#alert {
color: red;
margin: 1em 0;
}
</style>
<script type="text/javascript">
window.addEventListener('load', init, false);
function init() {
checkForFileApiSupport();
document.getElementById('files').addEventListener('change', handleFileSelection, false);
}
function checkForFileApiSupport() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
// All the File APIs are supported.
}
else {
document.getElementById('alert').innerHTML = "The File APIs are not fully supported in this browser.";
}
}
function handleFileSelection(evt) {
var files = evt.target.files; // The files selected by the user (as a FileList object).
// "files" is a FileList of file objects. List some file object properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', f.name, '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate, '</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
</script>
</head>
<body>
<input type="file" id="files" name="files[]" multiple /> <!-- The name attribute value is typically paired with the field's data when submitted via a <form> tag. -->
<output id="list"></output>
<div id="alert"></div>
</body>
</html>
Is it possible to restrict selection to a single file in the Open dialog rather than using f = files[0]
which may not always be reliable?
是否可以在“打开”对话框中将选择限制为单个文件,而不是使用f = files[0]
可能并不总是可靠的文件?
回答by jbalsas
If you don't want the user to be able to select more than one file, you should remove the multiple
attribute from the tag.
如果您不希望用户能够选择多个文件,则应multiple
从标记中删除该属性。
Change
改变
<input type="file" id="files" name="files[]" multiple />
<input type="file" id="files" name="files[]" multiple />
for
为了
<input type="file" id="file" name="file" />
<input type="file" id="file" name="file" />
You can check the full list of attributes for the input-type file tag here
您可以在此处查看输入类型文件标签的完整属性列表