上传时限制jquery中的图片大小

时间:2019-03-22 04:37:07

标签: javascript jquery html input

我正在使用以下脚本上传图像,它会检查它是否为有效图像。如果图片无效,则显示警告消息以再次重新上传。它工作正常..但是如何也检查图像大小...假设小于500 Kb,如果用户上传的图像大于500 Kb ...显示一个相同的警报消息框,以上传小于所需大小的图像500kb

这是我的代码

$("#fileUpload_one").on('change', function () {
  //Get count of selected files
  var countFiles = $(this)[0].files.length;
  var imgPath = $(this)[0].value;
  var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
  var image_holder = $("#image-holder_one");
  image_holder.empty();
  if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
    if (typeof (FileReader) != "undefined") {
      //loop for each file selected for uploaded.
      for (var i = 0; i < countFiles; i++) {
        var reader = new FileReader();
        reader.onload = function (e) {
          $("<img />", {
            "src": e.target.result,
            "class": "thumb-image",
            "height": "200px",
            "width": "200px"
          }).appendTo(image_holder);
        }
        image_holder.show();
        reader.readAsDataURL($(this)[0].files[i]);
      }
    } else {
      alert("This browser does not support FileReader.");
    }
  } else {
    alert("Pls select only images");
  }
});
<input id="fileUpload_one" type="file" multiple />
<div id="image-holder_one"></div>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

谢谢。

1 个答案:

答案 0 :(得分:0)

if (typeof (FileReader) != "undefined") {
      //loop for each file selected for uploaded.
      for (var i = 0; i < countFiles; i++) {
        var reader = new FileReader();
        reader.onload = function (e) {
          $("<img />", {
            "src": e.target.result,
            "class": "thumb-image",
          }).appendTo(image_holder);
          $(".thumb-image").css({'width' : '200px','height' : '200px'});

        }
        image_holder.show();
        reader.readAsDataURL($(this)[0].files[i]);
      }
    }