[英]get file size before upload with javascript
this is html code : 这是html代码:
<form method="POST" action="http://my-site.com/send-file" accept-charset="UTF-8" enctype="multipart/form-data">
<input name="_token" type="hidden" value="6Yav0H6Cyp62Rhr6uAAEefzL7Yq0BqIHfhuYwzy4">
<label for="file">File</label>
<input id="iefile" name="img" type="file">
<input type="submit" value="send">
</form>
this is js code : 这是js代码:
$('form').submit(function(e) { // capture submit
e.preventDefault();
size=$(this).find("input:file").files[0].size ;
alert(size);
}
but in console this error displayed : 但是在控制台中显示此错误:
Uncaught TypeError: Cannot read property '0' of undefined
To retrieve properties of DOM elements you should use .prop()
: 要检索DOM元素的属性,应使用
.prop()
:
$(this).find("input:file").prop('files')[0].size
This is because $(this).find()
returns a jQuery object and not the DOM element directly. 这是因为
$(this).find()
返回一个jQuery对象,而不是直接返回DOM元素。 Alternatively, you can treat the results as an array and use the first element like so: 或者,您可以将结果视为数组,并使用第一个元素,如下所示:
$(this).find("input:file")[0].files[0].size
As mentioned in the comments, you should also make sure a file was selected first: 正如所提到的意见,你也应该确保文件是第一选择:
var f = $(this).find("input:file")[0].files[0];
if (f) {
// do something with f.size
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.