jQuery简单验证上传文件大小及类型的方法


本文实例讲述了jQuery简单验证上传文件大小及类型的方法。分享给大家供大家参考,具体如下:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="jquery1.8/jquery-1.8.0.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#myFile").change(function () {
        var filepath = $("input[name='myFile']").val();
        var extStart = filepath.lastIndexOf(".");
        var ext = filepath.substring(extStart, filepath.length).toUpperCase();
        if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
          alert("图片限于bmp,png,gif,jpeg,jpg格式");
          $("#fileType").text("")
          $("#fileSize").text("");
          return false;
        } else { $("#fileType").text(ext) }
        var file_size = 0;
        if ($.browser.msie) {
          var img = new Image();
          img.src = filepath;
          while (true) {
            if (img.fileSize > 0) {
              if (img.fileSize > 3 * 1024 * 1024) {
                alert("图片不大于100MB。");
              } else {
                var num03 = img.fileSize / 1024;
                num04 = num03.toFixed(2)
                $("#fileSize").text(num04 + "KB");
              }
              break;
            }
          }
        } else {
          file_size = this.files[0].size;
          var size = file_size / 1024;
          if (size > 10240) {
            alert("上传的图片大小不能超过10M!");
          } else {
            var num01 = file_size / 1024;
            num02 = num01.toFixed(2);
            $("#fileSize").text(num02 + " KB");
          }
        }
        return true;
      });
    });
  </script>
  <title>无标题文档</title>
</head>
<body>
  <table width="500" cellspacing="0" cellpadding="0">
    <tr>
      <td width="72" id="fileType">
      </td>
      <td width="242">
        <input type="file" name="myFile" id="myFile" />
      </td>
      <td width="184" id="fileSize" class="fileSize">
      </td>
    </tr>
  </table>
</body>
</html>

PS:这里再为大家推荐几款代码格式化、美化工具,相信大家在以后的开发过程中会用得到:

在线JavaScript代码美化、格式化工具:
http://tools.phpstudy.net/code/js

JavaScript压缩/格式化/加密工具:
http://tools.phpstudy.net/code/jscompress

C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.phpstudy.net/code/ccode_html_css_json

XML代码在线格式化美化工具:
http://tools.phpstudy.net/code/xmlcodeformat

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.phpstudy.net/code/jsoncodeformat

在线JSON代码检验、检验、美化、格式化工具:
http://tools.phpstudy.net/code/json

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery常用插件及用法总结》、《jquery中Ajax用法总结》、《jQuery表格(table)操作技巧汇总》、《jQuery拖拽特效与技巧总结》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》及《jquery选择器用法总结》

希望本文所述对大家jQuery程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3