jQuery想要获取上传文件大小,可以使用file.size方法来以字节为单位显示文件大小。先获取到上传文件,然后使用file.size方法来获取该文件的大小。
做法:
● 单击浏览按钮选择上传文件。
● 选择文件后,调用显示所选文件大小的函数。
● 函数使用file.size方法以字节为单位显示文件大小。
示例1:向input [type = file]元素添加事件,当用户上传文件时,文件大小将在屏幕上输出
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="UP" style= "font-size: 15px; font-weight: bold;">
从系统中选择文件以获取文件大小
</p>
<input type="file" id="File" />
<br><br>
<p id="DOWN" style= "color:green; font-size: 20px; font-weight: bold;"></p>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('#File').on('change', function() {
$('#DOWN').text(this.files[0].size + "字节");
});
</script>
</body>
</html>示例2:向input[type=file]元素添加一个事件,当用户上载文件时,文件的大小将在屏幕上打印。这个例子允许用户上传小于2MB的文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="UP" style= "font-size: 15px; font-weight: bold;">
从系统中选择文件以获取文件大小
</p>
<input type="file" id="File" />
<br><br>
<p id="DOWN" style= "color:green; font-size: 20px; font-weight: bold;"></p>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('#File').on('change', function() {
if (this.files[0].size > 2097152) {
alert("尝试上传小于2MB的文件!");
} else {
$('#DOWN').text(this.files[0].size + "字节");
}
});
</script>
</body>
</html>大家可以预览看下效果。






网友评论文明上网理性发言 已有0人参与
发表评论: