如何检查是否使用javascript选择了文件?
问题描述:
在php中,您可以检查文件是否被选中:
In php this is how you would check if a file is selected:
$_FILES['item']['size']>0
在JavaScript中怎么样?
what about in JavaScript?
我需要知道,因为我有一个仅在选择文件时才有效的功能。
I need to know because I have a function that will only work if a file is selected.
答
http://www.w3.org/TR/ DOM-Level-2-HTML / html.html#ID-49531485 说:
DOMString类型的值
当元素的type属性具有值text时, file 或password,这表示交互式用户代理中相应表单控件的当前内容。
value of type DOMString
When the type attribute of the element has the value "text", "file" or "password", this represents the current contents of the corresponding form control, in an interactive user agent.
<html>
<head><title>...</title>
<script type="text/javascript">
function foo() {
var f = document.getElementById("f1");
alert( ""==f.value ? "nothing selected" : "file selected");
}
</script>
</head>
<body>
<form>
<div>
<input id ="f1" type="file" name="x" />
</div>
</form>
<button onclick="foo()">click</button>
</body>
</html>