如何使用jQuery获取上传文件大小
当用户使用JQuery上传文件时,如何获取文件大小?下面本篇文章就来给大家介绍一下使用jQuery获取上传文件大小的方法,希望对大家有所帮助。
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>
在选择文件之前:
选择文件后(大小>2MB):
以上就是如何使用jQuery获取上传文件大小?的详细内容,更多请关注html中文网其它相关文章
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。