首页 > 解决方案 > 无法验证上传的图片类型

问题描述

我正在按照教程系列制作一个 Android 壁纸应用程序。为此,我必须设计和创建管理图像的管理区域。我对图像验证感到震惊。我在下面粘贴了我的整个代码。

<h1>Catogeries</h1>
<hr>
<div class="row">
  <div class="col-lg-5">
    <h1>Add new</h1>
    <form class="form-group">
      <div>
        <label for="Catogery-name">Enter name</label>
        <input type="text" class="form-control" id="Catogery-name">
        <div class="invalid-feedback">Please enter a catogery name</div>
      </div>
      <div>
        <label for="Catogery-description">Description</label>
        <input type="text" class="form-control" id="Catogery-description">
        <div class="invalid-feedback">Please enter the valid description</div>
      </div>
      <div>
        <label for="Catogery-thumbnail">Thumbnail</label>
        <input type="file" class="form-control" id="Catogery-thumbnail">
        <div class="invalid-feedback">Please upload a valid image</div>
      </div>
      <div class="form-group" style="margin-top:3%">
        <img src="#" id="selected-thumbnail" width="250px" height="150px">
      </div>
      <div class="form-group">
        <div class="progress" style="margin-top:2%">
          <div class="progress-bar" style="width:0%" id="upload-progress">0%</div>
        </div>
      </div>
      <div class="btn btn-primary" type="button" id="save-catogery">Save</div>
    </form>
    <div id="result">

    </div>
  </div>
  <div class="col-lg-7">
    <h1>Saved Catogeries</h1>
  </div>
</div>
<script>
  var validImageTypes = ["image/gif", "image/jpeg", "image/png"];
  $("#selected-thumbnail").hide();

  function previewThumbnail(thumbnail) {
    if (thumbnail.files && thumbnail.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $("#selected-thumbnail").attr('src', e.target.result);
        $("#selected-thumbnail").fadeIn();
      }
      reader.readAsDataURL(thumbnail.files[0]);
    }
  }
  $("#Catogery-thumbnail").change(function() {
    previewThumbnail(this);
  });

  $("#save-catogery").click(function() {
    var catName = $("#Catogery-name").val();
    var desc = $("#Catogery-description").val();
    var thumbnail = $("#Catogery-thumbnail").prop("files")[0];

    if (!catName) {
      $("#Catogery-name").addClass("is-invalid");
      return;
    }
    if (!desc) {
      $("#Catogery-description").addClass("is-invalid");
      return;
    }
    if (thumbnail == null) {
      $("#Catogery-thumbnail").addClass("is-invalid");
      return;
    }
    if ($.inArray(thumbnail["type"], validImageTypes) < 0) {
      $("#Catogery-thumbnail").addClass("is-invalid");
      return;
    }
  });
</script>

标签: javascriptjqueryhtmlcssbootstrap-4

解决方案


推荐阅读